javascript get x and y coordinates on mouse click

前端 未结 3 2151
甜味超标
甜味超标 2020-11-27 16:07

I have a little div tag that when I click it (onClick event), it will run the printMousePos() function. This is the HTML tags:

<
相关标签:
3条回答
  • 2020-11-27 16:24

    simple solution is this:

    game.js:

    document.addEventListener('click', printMousePos, true);
    function printMousePos(e){
    
          cursorX = e.pageX;
          cursorY= e.pageY;
          $( "#test" ).text( "pageX: " + cursorX +",pageY: " + cursorY );
    }
    
    0 讨论(0)
  • 2020-11-27 16:34

    Like this.

    function printMousePos(event) {
      document.body.textContent =
        "clientX: " + event.clientX +
        " - clientY: " + event.clientY;
    }
    
    document.addEventListener("click", printMousePos);

    MouseEvent - MDN

    MouseEvent.clientX Read only
    The X coordinate of the mouse pointer in local (DOM content) coordinates.

    MouseEvent.clientY Read only
    The Y coordinate of the mouse pointer in local (DOM content) coordinates.

    0 讨论(0)
  • 2020-11-27 16:36

    It sounds like your printMousePos function should:

    1. Get the X and Y coordinates of the mouse
    2. Add those values to the HTML

    Currently, it does this:

    1. Creates (undefined) variables for the X and Y coordinates of the mouse
    2. Attaches a function to the "mousemove" event (which will set those variables to the mouse coordinates when triggered by a mouse move)
    3. Adds the current values of your variables to the HTML

    See the problem? Your variables are never getting set, because as soon as you add your function to the "mousemove" event you print them.

    It seems like you probably don't need that mousemove event at all; I would try something like this:

    function printMousePos(e) {
        var cursorX = e.pageX;
        var cursorY = e.pageY;
        document.getElementById('test').innerHTML = "x: " + cursorX + ", y: " + cursorY;
    }
    
    0 讨论(0)
提交回复
热议问题