<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<style>
#box1{
width: 100px;
height: 100px;
background-color: red;
position: absolute;
}
#box2{
width: 100px;
height: 100px;
background-color: yellowgreen;
position: absolute;
left: 200px;
top: 200px;
}
</style>
<script>
window.onload=function () {
var box1=document.getElementById("box1");
day(box1);
//绑定按下拖拽函数
function day(obj) {
box1.onmousedown=function (event) {
//判断兼容
if(obj.setPointerCapture(1)){
obj.setPointerCapture(1);
}
event=event||window.event;
//获取偏移量
var ol=event.clientX-obj.offsetLeft;
var ot=event.clientY-obj.offsetTop;
//移动函数
document.onmousemove=function (event) {
event=event||window.event;
//获取鼠标位置
var left=event.clientX-ol;
var top=event.clientY-ot;
//修改box1位置
obj.style.left=left+"px";
obj.style.top=top+"px";
};
//松开鼠标时将拖拽元素固定在当前位置
document.onmouseup=function () {
//将按下和拖动事件取消
document.onmousemove=null;
document.onmouseup=null;
//取消全选拖动
obj.releasePointerCapture(1);
};
return false;
};
}
}
</script>
</head>
<body>
<div id="box1"></div>
<div id="box2"></div>
<lu><li>1231321</li></lu>
</body>
</html>
拖拽事件
最新推荐文章于 2024-03-09 23:17:44 发布