<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>\<style type="text/css">
#box1{
height: 100px;
width: 100px;
background-color: hotpink;
position: absolute;
}
</style>
</head>
<body>
<div id="box1"></div>
<script type="text/javascript">
window.onload=function () {
var box1=document.getElementById("box1");
document.onmousemove=function (event) {
event=event||window.event;
var left=event.pageX;
var top=event.pageY;
box1.style.left=left-50+"px";
box1.style.top=top-50+"px";
}
}
</script>
</body>
</html
但是上述代码存在一定问题
为了解决上述问题,我又做了修改
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>\<style type="text/css">
#box1{
height: 100px;
width: 100px;
background-color: hotpink;
position: absolute;
}
</style>
</head>
<body>
<div id="box1"></div>
<script type="text/javascript">
window.onload=function () {
var box1=document.getElementById("box1");
document.onmousemove=function (event) {
event=event||window.event;
var left=event.clientX;
var top=event.clientY;
var st=document.body.scrollTop||document.documentElement.scrollTop;
var sl=document.body.scrollLeft||document.documentElement.scrollLeft;
box1.style.left=left+st-50+"px";
box1.style.top=top+sl-50+"px";
}
}
</script>
</body>
</html>