Mouse position - Cross browser compatibility - Javascript

一笑奈何 提交于 2019-11-27 14:58:38

问题


working with the mouse within Javascript I have occasionally met the following event attributes:

  • clientX, clientY
  • layerX, layerY
  • offsetX, offsetY
  • pageX, pageY
  • screenX, screenY
  • x, y

I'm wondering what their cross-browser compatibility looks like in general, as I have only found bits and pieces of info that I'm trying to patch up together.

Thanks guys


回答1:


Here is how jQuery does it :

// Calculate pageX/Y if missing and clientX/Y available
if ( event.pageX == null && event.clientX != null ) {
  var doc = document.documentElement, body = document.body;
  event.pageX = event.clientX + (doc && doc.scrollLeft || body && body.scrollLeft || 0) - (doc && doc.clientLeft || body && body.clientLeft || 0);
  event.pageY = event.clientY + (doc && doc.scrollTop  || body && body.scrollTop  || 0) - (doc   && doc.clientTop  || body && body.clientTop  || 0);
}

Testing pageX (or pageY) or calculating it from clientX and scrollLeft ans clientLeft



来源:https://stackoverflow.com/questions/3343384/mouse-position-cross-browser-compatibility-javascript

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!