HLJ 发布于
2019-09-23 14:07:38

Js event对象offsetX,pageX,screenX,clientX详解

平时在测量元素位置时难以确定,下面给出具体的event对象中的各种属性,以便日后使用。
 
检测相对于浏览器的位置:clientX和clientY
    当鼠标事件发生时,鼠标相对于浏览器左上角的位置
    
检测相对于文档的位置:pageX和pageY
    当鼠标事件发生时,鼠标相对于文档左上角的位置。(IE7/8无)(类似于event.clientX和event.clientY)
 
       检测相对于屏幕的位置:screenX和screenY
    当鼠标事件发生时,鼠标相对于屏幕左上角的位置
 
       检测相对于事件源的位置:offsetX和offsetY
    当鼠标事件发生时,鼠标相对于事件发生元素左上角的位置
 

不同浏览器对event事件的兼容:

  

tip: 让Firefox支持offsetX、offsetY

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
//计算光标相对于第一个定位的父元素的坐标
function coordinate(e){
  var o = window.event || e,
      coord,
      coord_X,
      coord_Y;
 
  coord_X = (o.offsetX === undefined) ? getOffset(o).X : o.offsetX;
  coord_Y = (o.offsetY === undefined) ? getOffset(o).Y : o.offsetY;
  coord = { "coord_X" : coord_X , "coord_Y" : coord_Y };
  return coord;
}
function getOffset(e){
  var target = e.target, // 当前触发的目标对象
      eventCoord,
      pageCoord,
      offsetCoord;
 
  // 计算当前触发元素到文档的距离
  pageCoord = getPageCoord(target);
 
  // 计算光标到文档的距离
  eventCoord = {
    X : window.pageXOffset + e.clientX,
    Y : window.pageYOffset + e.clientY
  };
 
  // 相减获取光标到第一个定位的父元素的坐标
  offsetCoord = {
    X : eventCoord.X - pageCoord.X,
    Y : eventCoord.Y - pageCoord.Y
  };
  return offsetCoord;
}
文章来源:https://www.cnblogs.com/bigharbour/p/11419670.html
最后生成于 2023-06-18 18:34:55
此内容有帮助 ?
0