1.实现效果:鼠标移动到哪,小天使跟到哪
2.思路:
(1)为了让鼠标在天使的中央,可以将横坐标和纵坐标分别减去天使高度和宽度的一半。
(2)注意设置top和left的值的时候,不要忘记加px
3.代码:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>跟随鼠标移动的天使</title>
<style>
img {
position: absolute;
top: 0px;
}
</style>
</head>
<body>
<img src="天使.png" alt="">
<script>
var img = document.querySelector('img');
document.addEventListener('mouseover',function(e) {
//千万不要忘记加px值
img.style.left = e.pageX-40+'px';
img.style.top = e.pageY+50+'px';
})
</script>
</body>
</html>