具体效果需要自己测试,也可以将div换成图片之类的。
这里用的div:
代码如下:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>图片随鼠标移动</title>
<style type="text/css">
#box1{
width: 50px;
height: 50px;
background: greenyellow;
position: absolute;
}
</style>
<script type="text/javascript">
window.onload = function () {
var box1 = document.getElementById("box1");
document.onmousemove = function (event) {
event = event || window.event;/*||为或语句,当IE不能识别event时候,就执行window.event 赋值*/
var st = document.body.scrollTop || document.documentElement.scrollTop;
var sl = document.body.scrollLeft|| document.documentElement.scrollLeft;
var left = event.clientX;
var top = event.clientY;
console.log(left);
console.log(top);
/*将鼠标的位置赋值给box1*/
box1.style.left = left+sl+"px";
box1.style.top = top+st+"px";
}
}
</script>
</head>
<body style="height: 1000px;width: 2000px;">
<div id="box1"></div>
</body>
</html>