這篇文章為大家介紹js如何實現圖片跟隨滑鼠移動,這裡會列舉兩種實作方法,希望對需要的朋友有幫助!
這裡列舉了兩種實作方法:
第一種
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
<style type="text/css">
img{
position: fixed;
left: 0px;
top: 0px;
}
</style>
</head>
<body>
<img src="icon_2.png" >
<script type="text/javascript">
var img = document.querySelector('img');
// mousemove滑鼠移動事件 document.addEventListener('mousemove',function(e){
var pagex = e.pageX-20+'px';
var pagey = e.pageY-20+'px';
// console.log(pagex,pagey);
img.style.left = pagex;
img.style.top = pagey;
})
</script>
</body>
</html>
第二種
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
<style type="text/css">
img{
position: absolute;
width: 80px;
}
</style>
</head>
<body>
<img src="皮影.jpg" id="img">
<script type="text/javascript">
window.onmousemove = function(e){
var x = e.pageX;
var y = e.pageY;
img.style.left = x+'px';
img.style.top = y+'px';
}
</script>
</body>
</html>
相關推薦:【JavaScript影片教學】
以上就是js實現圖片跟隨滑鼠移動的兩種方法的詳細內容,更多請關注php中文網其它相關文章!