<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
<style type="text/css">
#box1{
width:100px;
height:100px;
background-color: red;
position:absolute;
}
#box2{
width:100px;
height:100px;
background-color: aqua;
position: absolute;
left:200px;
top:200px;
}
</style>
<script type="text/javascript">
window.function(){
/**
* 拖拽box1元素
* - 拖拽流程
* 鼠标按下时开始拖拽
* 鼠标移动就移动
* 当鼠标松开时,停止
*
*/
var box1=document.getElementById("box1");
box1.function(event){
//div的偏移量鼠标.clientX-元素.offsetLeft
//div的偏移量鼠标.clientY-元素.offsetTop边缘的偏移量
event=event||window.event;
var ol=event.clientX-box1.offsetLeft;
var ot=event.clientY-box1.offsetTop;
// alert("开始拖拽");
//为document绑定一个onmousemove事件
document.function(event){
//alert("kaihsiyidon");
//当鼠标移动时,鼠标的位置改变了
event=event||window.event;
//获取鼠标的坐标
var left=event.clientX-ol;
var top=event.clientY-ot;
//修改box1的位置
box1.style.left=left+"px";
box1.style.top=top+"px";
};
//当鼠标松开时box1被固定
//绑定到document防止被遮住按不到
document.function(){
//取消document.onmousemove事件
document.null;
//取消document.onmouseup事件
document.null;
};
/**
* 当我们拖拽一个网页中的内容时,浏览器会默认去搜索引擎中搜索的内容,
* 此时会导致拖拽功能的异常,这是浏览器默认行为
* 如果不希望发生这个,就可以通过return false去取消
* 但是与ie8不兼容
*
* btn.setCatpue();捕获所有事件揽到自身,广告的毒瘤
* btn.releaseCapture()释放上面流氓的行为,取消
*/
return false;
};
};
</script>
</head>
<body>
<div id="box1"></div>
<div id="box2"></div>
</body>
</html>
div的拖拽,改进版本
最新推荐文章于 2025-07-04 13:24:06 发布