jQuery jquery鼠标位置相对窗口

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3526457/
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-26 15:36:05  来源:igfitidea点击:

jquery mouse position relative window

positionjquery

提问by user425772

I'm trying to get the exact mouse position relative to the window.

我试图获得相对于窗口的确切鼠标位置。

Here is my issue...

这是我的问题...

  • document.height= 1600 (actual document size)
  • window.height= 400 (viewable)
  • document.height= 1600(实际文档大小)
  • window.height= 400(可见)

I need to figure out the mouse position relative to the window, not to the document which the pageY attribute provides.

我需要弄清楚鼠标相对于窗口的位置,而不是 pageY 属性提供的文档。

It's for a large tooltip, which gets popped in on mouesover for a table item. If there is not enough room at the bottom of the screen (window is maxed), then the tooltip get displayed above the pointer, otherwise, below the pointer. This works fine until the document size is greater than pagesize (long table).

这是一个大的工具提示,它会在鼠标悬停时弹出一个表格项目。如果屏幕底部没有足够的空间(窗口已最大化),则工具提示将显示在指针上方,否则显示在指针下方。这工作正常,直到文档大小大于页面大小(长表)。

Thanks, Luc

谢谢,卢克

回答by Nick Craver

You can subtract .scrollTop()of the windowfrom pageY to get the position in the window, like this:

您可以减去.scrollTop()window从pageY得到的位置在窗口,如下所示:

var top = e.pageY - $(window).scrollTop();

You can give it a try here, take a look at the console.

你可以在这里试一试,看看控制台

回答by Marian

And what about window.pageYOffset?

那么 window.pageYOffset 呢?

Demo:

演示:

<html>
<head>
<style>
    html,body {padding:0;margin:0}
    #content {height:2048px;background-color:#ccc;}
    #status {position:fixed;top:0;left:0;}
</style>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<script type="text/javascript">
jQuery(document).ready(function(){
   $(document).mousemove(function(e){
      $('#status').html(e.pageX +', '+ (e.pageY - window.pageYOffset));
   }); 
})
</script>
<body>
<h2 id="status">0, 0</h2>
<div id="content"></div>
</body>
</html>

回答by Jimba Tamang

function showCoords(evt){
  alert(
    "clientX value: " + evt.clientX + "\n"
    + "clientY value: " + evt.clientY + "\n"
  );
}

I think this is what you are looking for. See in details here from Mozilla Developer.

我想这就是你要找的。在此处从 Mozilla Developer了解详细信息。

回答by jpluijmers

How about the document.body.scrollTop attribute, this contains the pixels you have scrolled. I believe a simple pageY - scrollTop should suffice then?

document.body.scrollTop 属性如何,它包含您滚动的像素。我相信一个简单的 pageY - scrollTop 就足够了吗?