- 需求分析:移动鼠标,改变图片的位置
- 思路分析:
- 1.监听鼠标在网页的移动事件 网页:window 鼠标移动:onmousemove
- 2.让图片的位置与事件对象的触发点位置一直 界面元素定位 相对于 页面的左上角距离
<!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>事件对象 - 天使跟随</title>
<style>
* {
margin: 0;
padding: 0;
/* 鼠标消失 */
cursor: none;
}
img {
position: absolute;
left: 0;
top: 0;
/* border: 1px solid #cff; */
}
</style>
</head>
<body>
<img src="./images/tianshi.gif" alt="" />
</body>
<script>
// 需求: 鼠标到哪,图片到哪
// 鼠标移动事件: onmousemove, 做移动事件的时候: 鼠标的移动范围
// 整个页面移动: 事件源应该是: window document (千万不能给body: body没有高度)
const img = document.querySelector("img");
// 页面做鼠标移动时间(window)
window.onmousemove = function (e) {
// 兼容
e = e || window.event;
// 鼠标有三大坐标系: 页面 可视 和 屏幕
// 没有滚动条: 页面 || 可视
// 为了防止产生滚动条: 页面
console.log(e.pageX, e.pageY);
// // low版本的图片移动: 移动到鼠标位置
// img.style.left = e.pageX + "px";
// img.style.top = e.pageY + "px";
// 高级版: 鼠标落在图片的中间 - 自身宽高的一半(offsetWidth/Height)
img.style.left = e.pageX - img.offsetWidth / 2 + "px";
img.style.top = e.pageY - img.offsetHeight / 2 + "px";
};
</script>
</html>