Home  >  Article  >  Web Front-end  >  Two ways to implement images that follow the mouse movement using js

Two ways to implement images that follow the mouse movement using js

藏色散人
藏色散人forward
2022-08-07 10:09:153486browse

This article will introduce to you how to implement js to implement pictures that follow the movement of the mouse. Here are two implementation methods. I hope it will be helpful to friends in need!

Here are two implementation methods:

The first one

<!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>


Second type

<!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>

Related recommendations: [JavaScript video tutorial]

The above is the detailed content of Two ways to implement images that follow the mouse movement using js. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:csdn.net. If there is any infringement, please contact admin@php.cn delete