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

posted @ 2022-04-02 09:48  coderwcb  阅读(226)  评论(0编辑  收藏  举报