在页面中,div将随着鼠标的移动而跟着移动,代码很简单,一看就懂
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title></title>
<style type="text/css">
#box1{
width: 100px;
height: 100px;
background-color: red;
/*
* 开启box1的绝对定位
*/
position: fixed;
}
</style>
<script type="text/javascript">
window.onload = function(){
/*
* 使div可以跟随鼠标移动
*/
//获取box1
var box1 = document.getElementById("box1");
//绑定鼠标移动事件
document.onmousemove = function(event){
//解决兼容问题
event = event || window.event;
//获取到鼠标的坐标
/*
* clientX和clientY
* 用于获取鼠标在当前的可见窗口的坐标
* div的偏移量,是相对于整个页面的
*/
var left = event.clientX;
var top = event.clientY;
//设置div的偏移量
box1.style.left = left + "px";
box1.style.top = top + "px";
};
};
</script>
</head>
<body style="height: 1000px;width: 2000px;">
<div id="box1"></div>
</body>
</html>