javascript:如何获得鼠标在窗口/浏览器/网页上的位置——可用于移动端

实际操作:【减去40像素,使得元素居中】

		var touch = e.originalEvent.targetTouches[0];
        var x = touch.pageX-document.body.scrollLeft - document.documentElement.scrollLeft-40;
        var y = touch.pageY- document.body.scrollTop - document.documentElement.scrollTop-40;

引用原文:


在web设计时,常常需要获得用户鼠标的坐标,可以用以下方法得到

 function  mouse_pos(e) 
 {
    
     
  if (!e) var e = window.event; 
  if (e.pageX || e.pageY)     {
    
     
     posx = e.pageX; 
     posy = e.pageY; 
  } 
  else if (e.clientX || e.clientY)    {
    
     
     posx = e.clientX + document.body.scrollLeft + document.documentElement.scrollLeft; 
     posy = e.clientY + document.body.scrollTop + document.documentElement.scrollTop; 
  } 
}

这里面的 posx,posy就是鼠标的坐标


详细解释:

引用:JavaScript获取鼠标位置的三种方法

https://blog.csdn.net/weixin_30859423/article/details/99602127
在一些DOM操作中我们经常会跟元素的位置打交道,鼠标交互式一个经常用到的方面,令人失望的是不同的游览器下会有不同的结果甚至是有的游览器下没结果,这篇文章就鼠标点击位置坐标获取做一些简单的总结。

获取鼠标位置首先要了解什么是event,event是一个声明了全局变量的一个对象,在chrome和IE下,可以随意访问,对于好奇的朋友console.log一下event。但!!!Firefox下是没有event这个对象的!!
好消息的是:在IE8,chrome下,是有event这个对象的!
鼠标点击位置坐标

相对于屏幕

如果是涉及到鼠标点击确定位置相对比较简单,获取到鼠标点击事件后,事件screenX,screenY获取的是点击位置相对于屏幕的左边距与上边距,不考虑iframe因素,不同游览器下表现的还算一致。

function getMousePos(event) {
    
    
      var e = event || window.event;
      return {
    
    'x':e.screenX,'y':screenY}
}

相对于浏览器窗口

简单代码即可实现,然而这时还不够,因为绝大多数情况下我们希望获取鼠标点击位置相对于游览器窗口的坐标,event的clientX,clientY属性分别表示鼠标点击位置相对于文档的左边距,上边距。

function getMousePos(event) {
    
    
      var e = event || window.event;
      return {
    
    'x':e.clientX,'y':clientY}
}

相对于文档

clientX与clientY是获取相对于当前屏幕的坐标,忽略了页面滚动因素,这在很多环境下很有用,但当我们需要考虑页面滚动,也就是相对于文档(body元素)的坐标时怎么办呢?只要加上滚动的位移就可以了。

在chrome可以通过document.body.scrollLeft,document.body.scrollTop计算出页面滚动位移,而在IE下可以通过document.documentElement.scrollLeft,document.documentElement.scrollTop

function getMousePos(event) {
    
    
       var e = event || window.event;
       var scrollX = document.documentElement.scrollLeft || document.body.scrollLeft;
       var scrollY = document.documentElement.scrollTop || document.body.scrollTop;
       var x = e.pageX || e.clientX + scrollX;
       var y = e.pageY || e.clientY + scrollY;
       //alert('x: ' + x + '\ny: ' + y);
       return {
    
     'x': x, 'y': y };
}

猜你喜欢

转载自blog.csdn.net/wwppp987/article/details/109160483