<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<style>
#box1{
width: 100px;
height: 100px;
background-color: red;
position: absolute;
/* 开启box1的绝对定位*/
}
</style>
<script>
window.onload=function (){
// 使div可以跟随鼠标移动
// 获取box1
var box1 = document.getElementById("box1");
//绑定鼠标移动事件
// document 获取的是整个页面
document.onmousemove = function (event){
// 获取鼠标的坐标
// clientX用于获取鼠标在当前窗口的可见窗口的坐标
// pageX,pageY获取鼠标相对于当前页面的坐标
//
// var left = event.clientX;
// var top = event.clientY;
var left = event.pageX;
var top = event.pageY;
// 设置div的偏移量
box1.style.left=left-50+"px";
box1.style.top=top-50+"px";
}
}
</script>
</head>
<body style="height: 1000px">
<div style="width: 500px; height: 500px; background-color: #ff5777"></div>
<div id="box1">
</div>
</body>
</html>
DOM实现div跟随鼠标移动
最新推荐文章于 2022-11-07 11:28:40 发布