图片跟着鼠标动js

时间:2022-02-06 02:13:31

<!DOCTYPE html>
<html>
<head>
<title>duisgf</title>
<meta charset="utf-8">
<style type="text/css">
#image{
position: relative;
left: 0px;
top: 0px;
}
</style>
</head>
<body>
<div>
<img src="flowers.jpg" id="image">
</div>
</body>
</html>
<script type="text/javascript">
var img = document.getElementById("image");
document.onclick = function(event){
var event = event || window.event;
targetX =event.clientX - img.offsetWidth/2;
targetY = event.clientY - img.offsetHeight/2;
}

var leaderX=0;
leaderY=0;
targetX=0;
targetY=0;
setInterval(function(){
leaderX = leaderX + (targetX - leaderX)/10;
leaderY = leaderY + (targetY - leaderY)/10;

img.style.left = leaderX+"px";
img.style.top = leaderY + "px";
},10)
</script>