写一个DIV跟随鼠标一起移动的例子
<!DOCTYPE html>
<html>
<head>
<title>javascript 鼠标事件偏移量的研究</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<style>
#movediv{
width:200px;
height:200px;
background-color: #FF0000;
cursor:pointer;
position:absolute;
}
</style>
<script>
window.onload = function () {
var movediv = document.getElementById("movediv");
movediv.onmousedown = function(event) {
event=event||window.event; //兼容IE8的写法
var offsetx=event.offsetX;
var offsety=event.offsetY;
document.onmousemove=function(event){
event=event||window.event;
var scrolltop=(document.documentElement && document.documentElement.scrollTop)||document.body.scrollTop; //解决浏览器兼容问题
var scrollleft=(document.documentElement && document.documentElement.scrollLeft)||document.body.scrollLeft; //解决浏览器兼容问题
//event.clientX event.clientY 鼠标的
movediv.style.left=event.clientX-offsetx+scrollleft+"px";
movediv.style.top=event.clientY-offsety+scrolltop+"px";
}
document.onmouseup=function(){
//一旦鼠标抬起,就要取消鼠标事件
document.onmousemove=null;
document.onmouseup=null;
}
}
};
</script>
</head>
<body style="height:3000px; width:3000px;">
<div id="movediv"></div>
</body>
</html>
网站声明:如果转载,请联系本站管理员。否则一切后果自行承担。
添加我为好友,拉您入交流群!
请使用微信扫一扫!