这篇文章我们来熟悉一下JavaScript 中关于 event 对象的位置属性,并附上图解方便理解。
JavaScript 中的event位置属性有:offsetX、offsetY、pageX、pageY、clientX、clientY、screenX、screenY、layerX、layerY、x、y。
首先我们先看一下个浏览器对这些属性的支持情况,如下图:
image.png
图解offsetX、clientX、pageX、screenX属性
image.png
layerX、layerY图解
image.png
event.x 和 event.y 的图解
image.png
测试代码如下:
<!DOCTYPE HTML>
<html lang="zh-cn">
<head>
<meta charset="utf-8"/>
<title>Javascript之event 位置属性解析</title>
<style>
body {
margin: 0;
padding: 0;
background: #ccc;
font-size: 12px;
overflow: auto;
}
.main {
width: 500px;
height: 330px;
position: relative;
margin: 250px auto 0;
background-color: #eee;
}
.box {
position: absolute;
width: 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>
作者:贵在随心
链接:http://www.jianshu.com/p/bc24c8bd6914
來源:简书
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。