<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
<style>
.box1{
width: 100px;
height: 100px;
background-color: blue;
/* 一定要写position,否则该实验完成不了. */
position: absolute;
}
</style>
<script>
window.onload = function(){
var box = document.getElementById('box');
// 绑定鼠标移动事件
document.onmousemove = function(event){
// 解决兼容性问题
// event = event || window.event;
/*
获取鼠标坐标:
clientX和clientY
用于获取鼠标在当前可控窗口的坐标
div偏移量,是相对与整个页面
pageX和pageY可以获取鼠标相对于页面的坐标
-但是这两个属性在IE8不兼容
*/
// var left = event.clientX;
// var top = event.clientY;
var left = event.pageX;
var top = event.pageY;
// 设置DIV的偏移量
box.style.left = left + 'px';
box.style.top = top + 'px';
}
}
</script>
<script>
</script>
</head>
<body style="height: 1000px; width: 2000px">
<div class="box1" id="box"></div>
</body>
</html>
JS基础-div跟随鼠标移动
最新推荐文章于 2022-10-26 09:14:21 发布