<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title></title>
<style>
body{
margin: 0;
padding: 0;
}
div{
width: 200px;
height:200px;
border: 1px solid #000000;
}
</style>
<script>
//判断鼠标是否按下
var isDown = false;
//实时监听鼠标位置
var moveX = 0;
var moveY = 0;
//记录鼠标按下瞬间的位置
var x = 0;
var y = 0;
鼠标按下时移动的偏移量
var mouseMoveX = 0;
var mouseMoveY = 0;
/* function myWheel(){
var cont = document.getElementById("cont");
cont.style.fontSize = "40px";
}
*/
//鼠标移动事件
function myMove(event){
moveX = event.clientX;
moveY = event.clientY;
var cont = document.getElementById("cont");
var mess2 = document.getElementById("mess2");
cont.innerHTML = "x="+moveX+",y="+moveY;
//计算鼠标移动偏移量
mouseMoveX = moveX - x;
mouseMoveY = moveY - y;
if(isDown){
mess2.innerHTML = "鼠标移动的偏移量为:x="+mouseMoveX+",y="+mouseMoveY;
}
}
//鼠标按下事件
function myDown(event){
x = event.clientX;
y = event.clientY;
isDown = true;
var mess = document.getElementById("mess");
mess.innerHTML = "鼠标按下了,当前鼠标位置:x="+x+",y="+y;
}
//鼠标松开事件
/*function myUp(){
var mess = document.getElementById("mess");
mess.innerHTML = "鼠标松开了";
isDown = false;
mouseMoveX = 0;
mouseMoveY = 0;
}*/
</script>
</head>
<body>
<div id="cont" onwheel="myWheel()" onmouseup="myUp()" onmousedown="myDown(event)" onmousemove="myMove(event)">
</div>
<font id="mess"></font><br>
<font id="mess2"></font>
</body>
</html>
javascript - 鼠标偏移量
最新推荐文章于 2023-06-09 10:00:00 发布
本文探讨了如何使用JavaScript获取鼠标相对于页面元素的精确偏移量。通过事件对象的clientX和clientY属性,结合元素的offsetLeft和offsetTop属性,可以计算出鼠标的实时位置信息,这对于实现交互式UI或者拖拽效果等应用场景非常有用。
摘要由CSDN通过智能技术生成