javascript 图解 event对象offsetX, clientX, pageX, screenX, layerX, x区别
首先需要知道clientX,clientY,screenX,screenY,offsetX,offsetY 是鼠标事件对象下的几个属性.所以必然是“鼠标事件”发生时候才会有意义;
一、不同浏览器对这些属性的支持:
二、作用及其测试
clientX:当鼠标事件发生时(不管是onclick,还是omousemove,onmouseover等),鼠标相对于浏览器(这里说的是浏览器的有效区域)x轴的位置;
clientY:当鼠标事件发生时,鼠标相对于浏览器(这里说的是浏览器的有效区域)y轴的位置;
screenX:当鼠标事件发生时,鼠标相对于显示器屏幕x轴的位置;
screenY:当鼠标事件发生时,鼠标相对于显示器屏幕y轴的位置;
offsetX:当鼠标事件发生时,鼠标相对于事件源x轴的位置
offsetY:当鼠标事件发生时,鼠标相对于事件源y轴的位置
x,y的取值和screenX,screenY得到的数相同
测试offsetX:鼠标是在接近demo按钮的左上角点击,可以发现是按照事件源的位置定位
代码如下
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>显示单击的坐标</title>
<style>
body{
margin: 0;
padding: 0;
}
div{
width: 500px;
height: 300px;
border: 1px solid red;
}
button{
width: 100px;
height:50px;
margin-top:50px;
}
</style>
<script type="text/javascript">
document.onmousemove = function(ev) {
var e = ev || window.event;
var div = document.getElementById('demo');
var btn=document.getElementsByTagName("button");
div.innerHTML = "clientX: " + e.clientX+ ",clientY:" + e.clientY +
"</br> screenX:" + e.screenX + ",screenY:" + e.screenY;
}
window.onload=function(){
var btn=document.getElementsByTagName("button")[0];
btn.onclick=function(ev){
var e = ev || window.event;
console.log("e.offsetX="+e.offsetX+"\n e.offsetY="+e.offsetY)
}
}
</script>
</head>
<body>
<div id="demo">
</div>
<button type="button">测试</button>
</body>
</html>
javascript offsetLeft,Left,clientLeft去区别:
https://blog.csdn.net/weixin_44797182/article/details/97979423
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· DeepSeek 开源周回顾「GitHub 热点速览」
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
· AI与.NET技术实操系列(二):开始使用ML.NET
· 单线程的Redis速度为什么快?