要求:
- 在瀏覽器頁面中,圖片實時跟隨鼠標
- 鼠標在圖片的中心位置
實現思路:
- 鼠標不斷移動,使用鼠標移動事件:
mousemove
- 在頁面中移動,給
document
注冊事件 - 圖片要移動距離,而且不占位置,使用絕對定位即可
- 每次鼠標移動,獲得最新的鼠標坐標,把這個
x
和y
坐標作為圖片的top
和left
值就可以移動圖片
代碼實現:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
img {
/* 因為圖片不能影響頁面其他的布局,所以用絕對定位 */
position: absolute;
}
</style>
</head>
<body>
<img src="https://img2020.cnblogs.com/blog/2171269/202010/2171269-20201010211141689-230895530.png" alt="">
<script>
var pic = document.querySelector('img');
document.addEventListener('mousemove', function(e) {
// 獲取當前鼠標到頁面的距離
var x = e.pageX;
var y = e.pageY;
// 選用圖片大小為50*50像素,讓鼠標居中在它中間,x左移25px,y上移25px
pic.style.left = x - 25 + 'px';
pic.style.top = y - 25 + 'px';
});
</script>
</body>
</html>
實現效果:
將代碼復制到記事本中,並改名為xx.html
,保存。使用瀏覽器打開即可。