div跟随鼠标移动
div跟随鼠标移动
<body style="width: 2000px;height: 1000px;">
<div id="box1" style="width: 100px;height: 100px;background-color: red;position: absolute;"></div>
</body>
<script>
window.onload = function(){
var box1 = document.getElementById('box1')
//给整个页面绑定:鼠标移动事件
document.onmousemove = function(event){
event = event||window.event
// 鼠标在页面的位置 = 滚动条滚动的距离 + 可视区域的坐标。
var pagex = event.pageX || scroll().left + event.clientX
var pagey = event.pageY || scroll().top + event.clientY
box1.style.left = pagex + 'px'
box1.style.top = pagey + 'px'
}
}
function scroll(){
return{
//此函数的返回值是对象
left:window.pageYOffset || document.body.scrollTop || document.documentElement.scrollTop,
right:window.pageXOffset || document.body.scrollLeft || document.documentElement.scrollLeft
}
}
</script>