<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>拖拽</title>
<script type="text/javascript">
window.onload = function () {
/*
* 拖拽box1元素
* -1.鼠标按下时,拖拽 鼠标按下事件:onmousedown
* -2.当鼠标移动时,被拖拽元素跟随鼠标移动 鼠标移动事件:onmousemove
* -3.鼠标松开时,被拖拽元素停止移动 鼠标松开事件:onmouseup
*/
var box1 = document.getElementById("box1");
var box2 = document.getElementById("box2");
drap(box1);
drap(box2);
/*
*用函数封装
*
*/
function drap(obj) {
var box1 = document.getElementById("box1");
obj.onmousedown = function (event) {
//先进性捕获事件
//set();
//只在ie中可用,在ie中不能用
obj.setCapture && box1.setCapture();
//alert("鼠标按下~~~~");
//div的偏移量,clientX-offsetLeft
//div的偏移量,clientY-offseTop
//兼容性问题
event = event || window.event;
var ol = event.clientX - obj.offsetLeft;
var ot = event.clientY - obj.offsetTop;
document.onmousemove = function (event) {
//兼容的处理
event = event || window.event;
//当鼠标移动时,被拖拽元素跟随鼠标移动 鼠标移动事件:onmousemove
var left = event.clientX - ol;
var right = event.clientY - ot;
obj.style.left = left + "px";
obj.style.top = right + "px";
};
//为document绑定鼠标松开事件
document.onmouseup = function () {
//鼠标松开时,被拖拽元素停止移动 鼠标松开事件:onmouseup
//取消document的onmousemove事件
document.onmousemove = null;
//取消document的onmouseup事件
document.onmouseup = null;
//alert("鼠标松开了");
obj.releaseCapture && obj.releaseCapture();
};
/*
*当我们拖曳一个网页中的内容时,浏览器会默认去搜索引擎中搜索内容
* 这样会导致拖拽功能异常,这是浏览器提供的默认行为
* 如果不希望发生这个行为,可以利用return false取消
*/
return false;
};
};
};
</script>
<style type="text/css">
#box1 {
width: 100px;
height: 100px;
background-color: red;
position: absolute;
}
#box2 {
width: 100px;
height: 100px;
background-color: yellow;
position: absolute;
top: 200px;
left: 200px;
}
</style>
</head>
<body>
我是一段文字
<div id="box1">
</div>
<div id="box2"></div>
</body>
</html>
2022/1/14,拖拽
最新推荐文章于 2024-08-16 19:02:09 发布