通过 3 张图和 1 张表格,轻松区别 JavaScript Event 对象中的offsetX, clientX, pageX, screenX, layerX, x等属性。
一、测试代码如下:
<!DOCTYPE HTML> <html lang="zh-cn"> <head> <meta charset="utf-8" /> <title>Javascript</title> <style> body{margin:0;padding:0;background:#ccc;font-size:12px;overflow:auto} .main{ 500px;height: 330px;position: relative;margin: 250px auto 0;background-color: #eee;} .box{position: absolute; 220px;height: 180px;background-color: orange;top: 80px;left: 80px;} </style> </head> <body style="height:1600px;"> <div class="main"> <div class="box" id="box"></div> </div> <script> var oBox = document.getElementById('box'); window.onload = function(){ oBox.onmousedown = function(ev){ ev = ev || window.event; console.log(ev.offsetX, ev.offsetY); console.log(ev.clientX, ev.clientY); console.log(ev.pageX, ev.pageY); console.log(ev.screenX, ev.screenY); console.log(ev.layerX, ev.layerY); console.log(ev.x, ev.y); } } </script> </body> </html>
二、不同浏览器对这些属性的支持:
三、图解 event.offsetX,event.clientX,event.pageX,event.screenX属性
四、图解 event.layerX,event.layerY 属性
五、图解 event.x,event.y 属性
++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
六、Jquery 兼容写法
jQuery event 事件对象,包含有 event.offsetX, event.clientX,event.pageX,event.screenX等属性(firefox 浏览器中, offsetX 为 undefined)。firefox 获取 offsetX / offsetY 的值,需要通过 event 对象的属性 originalEvent。
<script> $(function(){ $("#box").mousedown(function(event){ console.log(event.offsetX, event.offsetY); console.log(event.clientX, event.clientY); console.log(event.pageX, event.pageY); console.log(event.screenX, event.screenY); /* firefox */ console.log(event.originalEvent.layerX, event.originalEvent.layerY); }); }); </script>