onMouseMove get mouse position

匿名 (未验证) 提交于 2019-12-03 03:02:02

问题:

In javascript, within the javascript event hander for onMouseMove how do I get the mouse position in x, y corrdinates relative to the top of the page?

回答1:

if you can use jQuery, then this will help:

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 


回答2:

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').



回答3:

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))};



回答4:

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);   }; 


标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!