jquery mouse position relative window

2019-01-23 13:32发布

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)

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

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

4条回答
Explosion°爆炸
2楼-- · 2019-01-23 13:56
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.

查看更多
迷人小祖宗
3楼-- · 2019-01-23 14:00

And what about 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>
查看更多
等我变得足够好
4楼-- · 2019-01-23 14:14

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

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

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

查看更多
虎瘦雄心在
5楼-- · 2019-01-23 14:16

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

查看更多
登录 后发表回答