需求
通过JavaScript使盒子跟随着鼠标的移动而移动,并且当页面出现滚动条时,盒子也会跟随鼠标正常移动(兼容IE8)
代码
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>div跟随鼠标移动</title>
<style>
div{
width: 200px;
height: 200px;
background-color: skyblue;
/*注意此处需要设置盒子的定位方式,否则后面设置盒子的偏移量无效*/
position: absolute;
}
body{
width: 2000px;
height: 2000px;
}
</style>
<script>
window.onload = function () {
let box = document.getElementById("box");
let odj = document.documentElement;
odj.onmousemove = function (event) {
// 解决IE8对event的兼容性问题
event = event || window.event;
// 解决body和documentElement的兼容性问题(谷歌浏览器和其他浏览器的兼容性)
var st = document.body.scrollTop || document.documentElement.scrollTop;
var sl = document.body.scrollLeft || document.documentElement.scrollLeft;
//设置盒子的水平偏移量 注意需要加上单位
box.style.left = event.clientX + sl + "px";
//设置盒子的垂直偏移量
box.style.top = event.clientY + st + "px";
};
};
</script>
</head>
<body>
<div id="box"></div>
</body>
</html>
来源:oschina
链接:https://my.oschina.net/u/4314546/blog/3232661