<!DOCTYPE html>
<html>
<head>
< charset="UTF-8">
< > </ >
<style type="text/css">
#box1{
width:100px;
height:100px;
background-color:red;
/*开启box1的绝对定位*/
position:absolute;
}
</style>
< type="text/ ">
/*
*使div可以跟随鼠标移动
* */
window. = function(){
//获取box1
var box1 = document.getElementById("box1");
//绑定鼠标移动事件
document. = function(event){
//解决兼容问题
event = event || window.event;
//获取滚动滚动的距离。
//chrome认为滚动条是body。
//火狐等认为是浏览器的滚动条是html的。
var st = document.body.scrollTop || document.documentElement.scrollTop;
var sl = document.body.scrollLeft || document.documentElement.scrollLeft;
console.log(st);
//获取到鼠标的坐标
//用于获取鼠标在当前的可见窗口的坐标
//在IE8中不支持 兼容IE8 则不要使用
var left = event.clientX;
var top = event.clientY;
//设置div的偏移量
box1.style.left = left+ sl + "px";
box1.style.top = top+ st +"px";
}
}
</ >
</head>
<body style="height:5000px;">
<div id="box1">
</div>
</body>
</html>
<!DOCTYPE html>
<html>
<head>
< charset="UTF-8">
< > </ >
<style type="text/css">
#box1{
width:100px;
height:100px;
background-color:red;
/*开启box1的绝对定位*/
position:absolute;
}
</style>
< type="text/ ">
/*
*使div可以跟随鼠标移动
* */
window. = function(){
//获取box1
var box1 = document.getElementById("box1");
//绑定鼠标移动事件
document. = function(event){
//解决兼容问题
event = event || window.event;
//获取滚动滚动的距离。
//chrome认为滚动条是body。
//火狐等认为是浏览器的滚动条是html的。
var st = document.body.scrollTop || document.documentElement.scrollTop;
var sl = document.body.scrollLeft || document.documentElement.scrollLeft;
console.log(st);
//获取到鼠标的坐标
//用于获取鼠标在当前的可见窗口的坐标
//在IE8中不支持 兼容IE8 则不要使用
var left = event.clientX;
var top = event.clientY;
//设置div的偏移量
box1.style.left = left+ sl + "px";
box1.style.top = top+ st +"px";
}
}
</ >
</head>
<body style="height:5000px;">
<div id="box1">
</div>
</body>
</html>
继续阅读与本文标签相同的文章
-
OCP-052考试题库汇总(50)-CUUG内部解答版
2026-05-18栏目: 教程
-
Baseus倍思音频产品采用Bongiovi DPS软件算法 给用户带来沉浸式体验体验
2026-05-18栏目: 教程
-
90%的编程初学者,都遇到过这些问题!
2026-05-18栏目: 教程
-
有关厂商都在积极布局功率碳化硅
2026-05-18栏目: 教程
-
反向链接对网站权重有影响吗?
2026-05-18栏目: 教程
