您好,欢迎访问一九零五行业门户网

鼠标事件的screenY,pageY,clientY,layerY,offsetY属性详解_javascript技巧

screeny
         鼠标相对于显示器屏幕左上角的偏移
pagey
         鼠标相对于页面左上角的偏移 (其值不会受滚动条的影响)
         ie9之下并不支持这个属性
         但是可以写点代码计算出来。 jquery中的实现:
复制代码 代码如下:
// calculate pagex/y if missing and clientx/y available
 if ( event.pagex == null && original.clientx != null ) {
     eventdoc = event.target.ownerdocument || document;
     doc = eventdoc.documentelement;
     body = eventdoc.body;
     event.pagex = original.clientx + ( doc && doc.scrollleft || body && body.scrollleft || 0 ) - ( doc && doc.clientleft||body&&body.clientleft || 0 );
     event.pagey = original.clienty + ( doc && doc.scrolltop  || body && body.scrolltop  || 0 ) - ( doc && doc.clienttop  || body && body.clienttop  || 0 );
 }
简单点实现就是。 
鼠标相对于浏览器视口的偏移加上文档的滚动条隐藏的高度减去文档的clienttop.
复制代码 代码如下:
var pagey = event.clienty +document.documentelement. scrolltop-document.documentelement.clienttop
为何要减去document.documentelement.clienttop
这是ie8之下浏览器特有的文档的偏移,即使设置html,body的padding和margin为0也不会影响其值。
在ie7下测试,得到
复制代码 代码如下:
document.documentelement.clienttop --> 2px  document.documentelement.clientleft --> 2px
 document.bocy.clienttop --> 0px  document.body.clientleft --> 0px
clienty
         鼠标相对于浏览器视口左上角的偏移
         注意clienty和pagey的区别,clienty在页面无滚动条的情况下值等同于pagey
----------------------------------分割-----------------------------------------------
layery
         如果元素的position样式不是默认的static,我们说这个元素具有定位属性。
         在当前触发鼠标事件的元素和它的祖先元素中找到最近的具有定位属性的元素,计算鼠标与其的偏移值,以找到元素的border的左上角的外交点作为相对点。如果找不到具有定位属性的元素,那么就相对于当前页面计算偏移,此时等同于pagey。
ie9之下并不支持这个属性,但是可以用其特有的offsety替换
offsety  
   ie专有的属性
         offsety和layery的不同在于,前者的在计算偏移值时,相对于元素的border左上角的内交点,因此当鼠标位于元素的border上时,偏移值是一个负值。 另外offsety并不在乎触发事件的元素是否有定位属性,它总是相对于触发事件的元素来计算偏移值。
鉴于layery和offsety的不同,要兼容的使用二者要注意
         1.触发事件的元素一定要设置定位属性。
        2.在元素具有上边框border-top的情况下, layery比offsety的值多一个border-top的宽度值。
复制代码 代码如下:
//这里的element.bordertopwidth必须是实际计算出的元素的上边框宽度。
 var bordertopwidth =  window.getcomputedstyle ? window.getcomputedstyle(element,null).bordertopwidth: element.currentstyle.bordertopwidth;
 var offsety = event.offsety||(event.layery + bordertopwidth);
通过layery和offsety属性,可以很方便的计算鼠标相对于绑定鼠标事件元素的偏移,这在某些时候非常有用。   
这里详细说了鼠标竖直方向的偏移属性,水平方向的偏移类似,不再讨论。
以上就是本文的全部内容了,希望大家能够喜欢。
其它类似信息

推荐信息