要求:
- 在瀏覽器頁面中,圖片實時跟隨滑鼠
- 滑鼠在圖片的中心位置
實作思路:
- 滑鼠不斷移動,使用滑鼠移動事件:
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://img.uj5u.com/2020/10/10/136722102306421.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,保存,使用瀏覽器打開即可,
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/166823.html
標籤:JavaScript
