<!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>Document</title>
<style>
img {
position: absolute;
width: 100px;
/* top: 2px; */
z-index: 100px;
}
div {
position: absolute;
width: 100px;
height: 100px;
background-color: rgba(255, 255, 0, 0.4);
}
</style>
</head>
<body>
<div>1</div>
<img src="小天使.gif" alt="">
<script>
var pic = document.querySelector('img');
var div = document.querySelector('div')
document.addEventListener('mousemove', function(e) {
// 1. mousemove 只要我们鼠标移动1px 就会触发这个时间
// 2. 核心原理:每次鼠标移动,我们都会获得最新的鼠标坐标,把这个x和y坐标做为图片top和left值就可以移动图片。
var x = e.pageX;
var y = e.pageY;
// console.log('x坐标是' + x, 'y坐标是' + y);
// 3. 千万不要忘记给left 和top添加px单位
// pic.style.left = x - 50 + 'px';
// pic.style.top = y - 50 + 'px';
div.style.left = x - 50 + 'px';
div.style.top = y - 50 + 'px';
})
</script>
</body>
</html>