描述:
当用户点击页面的任意位置的时候,让控制的部件缓慢移动到该位置。
实现代码:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>鼠标跟随</title>
<style>
body{
height: 3000px;
}
img{
position:absolute;
padding: 10px 0;
cursor: pointer;
}
</style>
</head>
<body>
<img src="images/img.jpg" width="100"/></body>
</html>
<script>
//获取相关元素
var img = document.getElementsByTagName("img")[0];
var timer = null;
var targetx = 0; var targety = 0;
var leaderx = 0;var leadery = 0;
document.onclick = function (event) {
event = event || window.event;
//获取移动的位置
var pageY = event.pageY || scroll().top + event.clientY;
var pageX = event.pageX || scroll().left + event.clientX;
//让鼠标位于该空间的中心
targety = pageY - img.offsetHeight/2;
targetx = pageX - img.offsetWidth/2;
clearInterval(timer);
timer = setInterval(function () {
leaderx = img.offsetLeft;
//获取x轴方向的步长
var stepx = (targetx-leaderx)/10;
stepx = stepx>0?Math.ceil(stepx):Math.floor(stepx);
leaderx = leaderx+stepx;
img.style.left=leaderx+"px";
leadery=img.offsetTop;
//获取y轴方向的步长
var stepy=(targety-leadery)/10;
stepy = stepy>0?Math.ceil(stepy):Math.floor(stepy);
leadery = leadery+stepy;
img.style.top=leadery+"px";
if(Math.abs(targety-img.offsetTop)<=Math.abs(stepy) && Math.abs(targetx-img.offsetLeft)<=Math.abs(stepx)){
img.style.top=targety+"px";
img.style.left=targetx+"px";
clearInterval(timer);
}
},30);
}
function scroll(){
return {
"top": window.pageYOffset || document.body.scrollTop || document.documentElement.scrollTop,
"left": window.pageXOffset || document.body.scrollLeft || document.documentElement.scrollLeft
}
}
</script>