Javascript 鼠标悬停事件上的鼠标位置

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/14545626/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 17:09:17  来源:igfitidea点击:

Mouse position on mouseover event

javascriptmousemouseovermouse-position

提问by user2013107

Is it possible to get the exactly mouse position in a mouseouver event of a image? If i use a function that update the mouse position on document mouse move event I can have problems with delay and this kind of thing and wouldn't get the EXACTLY position

是否可以在图像的 mouseouver 事件中获得准确的鼠标位置?如果我使用在文档鼠标移动事件上更新鼠标位置的函数,我可能会遇到延迟和此类问题,并且无法获得准确的位置

回答by Mayur Manani

If you are looking for a simple JS to get the cursor position for a MouseOver event, here is the sample code:

如果您正在寻找一个简单的 JS 来获取 MouseOver 事件的光标位置,这里是示例代码:

    <!DOCTYPE html>
    <html>
    <head>
     <script>
     
     function getPos(e){
      x=e.clientX;
      y=e.clientY;
      cursor="Your Mouse Position Is : " + x + " and " + y ;
      document.getElementById("displayArea").innerHTML=cursor
     }
    
     function stopTracking(){
      document.getElementById("displayArea").innerHTML="";
     }
    
     </script>
    </head>
    
    <body>
     <div id="focusArea" onmousemove="getPos(event)" onmouseout="stopTracking()"><p>Mouse Over This Text And Get The Cursor Position!</p></div>
     
     <p id="displayArea"></p>
    </body>
    </html>

回答by Rajib Ganguly

The javascript method offset()used for tracking the position, and here I did the same as Mayur says, just little bit added.

offset()用于跟踪位置的 javascript 方法,在这里我和 Mayur 说的一样,只是添加了一点点。

See jsfiddle

见 jsfiddle