今天给朋友们分享js获取鼠标坐标的最全方法集合:
HTML、CSS与JS代码如下:
<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{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>
浏览器对这些属性的支持情况:
event.pageX与event.pageY有兼容问题,IE9之前不支持使用,如果IE9之前浏览器要获取光标在文档中的坐标,则使用 光标在视口中的坐标 + 滚动距离
event.clientY + (document.documentElement.scrollTop || document.body.scrollTop)
它们对应获取的距离是哪里:
event.layerX,event.layerY:
event.x,event.y: