获得的是鼠标可视区的鼠标坐标
myEvent.clientX / myEvent.clientY
获取页面的水平滚动条位置
document.documentElement.scrollLeft || document.body.scrollLeft
获取页面的数值滚动条位置
document.documentElement.scrollTop || document.body.scrollTop
示意图
div.style.top = clientY + scrollTop
shiyitu.png
<!DOCTYPE html>
<html>
<head lang="en">
<meta charset="UTF-8">
<title>跟着鼠标走的div</title>
<script>
function getPos(ev){
var myEvent = ev || event;
var x = myEvent.clientX + (document.documentElement.scrollLeft || document.body.scrollLeft);
var y = myEvent.clientY + (document.documentElement.scrollTop || document.body.scrollTop);
return {x:x , y:y};
}
window.onload = function(){
document.onmousemove = function(ev){
var div = document.getElementsByTagName("div")[0];
div.style.left =getPos(ev).x + "px";
div.style.top =getPos(ev).y + "px";
}
}
</script>
</head>
<body style="height:5000px;">
<div style="width: 100px;height:100px;background-color: red;position: absolute"></div>
</body>
</html>
效果
eventSport.gif
网友评论