onMouseMove get mouse position

空扰寡人 提交于 2019-11-27 02:03:53

if you can use jQuery, then this will help:

<div id="divA" style="width:100px;height:100px;clear:both;"></div>
<span></span><span></span>
<script>
    $("#divA").mousemove(function(e){
      var pageCoords = "( " + e.pageX + ", " + e.pageY + " )";
      var clientCoords = "( " + e.clientX + ", " + e.clientY + " )";
      $("span:first").text("( e.pageX, e.pageY ) - " + pageCoords);
      $("span:last").text("( e.clientX, e.clientY ) - " + clientCoords);
    });

</script>

here is pure javascript only example:

var tempX = 0;
  var tempY = 0;

  function getMouseXY(e) {
    if (IE) { // grab the x-y pos.s if browser is IE
      tempX = event.clientX + document.body.scrollLeft;
      tempY = event.clientY + document.body.scrollTop;
    }
    else {  // grab the x-y pos.s if browser is NS
      tempX = e.pageX;
      tempY = e.pageY;
    }  

    if (tempX < 0){tempX = 0;}
    if (tempY < 0){tempY = 0;}  

    document.Show.MouseX.value = tempX;//MouseX is textbox
    document.Show.MouseY.value = tempY;//MouseY is textbox

    return true;
  }

It might be a bit overkill to use d3.js just for finding mouse coordinates, but they have a very useful function called d3.mouse(*container*). Below is an example of doing what you want to do:

var coordinates = [0,0];
d3.select('html') // Selects the 'html' element
  .on('mousemove', function()
    {
      coordinates = d3.mouse(this); // Gets the mouse coordinates with respect to
                                    // the top of the page (because I selected
                                    // 'html')
    });

In the above case, the x-coordinate would be coordinates[0], and the y-coordinate would be coordinates[1]. This is extremely handy, because you can get the mouse coordinates with respect to any container you want to by exchanging 'html' with the tag (e.g. 'body'), class name (e.g. '.class_name'), or id (e.g. '#element_id').

Especially with mousemove events, that fire fast and furious, its good to pare down the handlers before you use them-

var whereAt= (function(){
    if(window.pageXOffset!= undefined){
        return function(ev){
            return [ev.clientX+window.pageXOffset,
            ev.clientY+window.pageYOffset];
        }
    }
    else return function(){
        var ev= window.event,
        d= document.documentElement, b= document.body;
        return [ev.clientX+d.scrollLeft+ b.scrollLeft,
        ev.clientY+d.scrollTop+ b.scrollTop];
    }
})()

document.ondblclick=function(e){alert(whereAt(e))};

Sayanjyoti Das

This is tried and works in all browsers:

   function getMousePos(e) {
       return {x:e.clientX,y:e.clientY};
   }

Now you can use it in an event like this:

  document.onmousemove=function(e) {
       var mousecoords = getMousePos(e);
       alert(mousecoords.x);alert(mousecoords.y);
  };
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!