鼠标移动事件div跟随鼠标
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title></title>
<script>
window.onload=function () {
var box1=document.getElementById("box1");
document.onmousemove=function (event) {
//解决兼容性问题
event=event||window.event;
//获取滚动条的距离/
// 解决兼容问题
var st=document.body.scrollTop||document.documentElement.scrollTop;
var sl=document.body.scrollLeft||document.documentElement.scrollLeft;
//获取鼠标的位置
//相对于页面用pageX pageY -------clientY不能直接用于有滚轮的页面
var left=event.clientX;
var top=event.clientY;
//设置偏移量
box1.style.left=left+sl+"px";
box1.style.top=top+st+"px";
}
}
</script>
<style>
#box1{
height: 100px;
width: 100px;
background-color: yellow;
position: absolute;
}
</style>
</head>
<body style="width: 2000px;height: 1000px">
<div id="box1"></div>
</body>
</html>
效果图