<!DOCTYPE html>
<html lang="zh">
<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>Document</title>
<style>
#box1{
width: 100px;
height: 100px;
background-color: yellow;
position: absolute;
}
#box2{
width: 100px;
height: 100px;
background-color: yellow;
}
</style>
<script>
window.onload=function(){
var box1=document.getElementById("box1");
//为box1绑定onmousedown响应事件
box1.onmousedown=function(event){
//div的偏移量鼠标.clentX -元素.offsetLeft
//div的偏移量鼠标.clentY -元素.offsetTop
var ol=event.clientX-box1.offsetLeft;
var ot=event.clientY-box1.offsetTop;
//为document绑定onmousemove响应事件
document.onmousemove=function(event){
var left=event.clientX-ol;
var top=event.clientY-ot;
box1.style.left=left+"px";
box1.style.top=top+"px";
};
//为document绑定onmouseup响应事件
document.onmouseup=function(){
document.onmousemove=null;
document.onmouseup=null;
};
/* 当我们拖拽一 个网页中的内容时,浏览器会默认去搜索引擎中搜索内容,
此时会导致拖拽功能的异常,这个是浏览器提供的默认行为,
如果不希望发生这个行为,则可以通过return false来取消默认行为 */
return false;
};
};
</script>
</head>
<body>
<div id="box1"></div>
<div id="box2"></div>
</body>
</html>
拖拽的练习
最新推荐文章于 2024-04-09 17:34:36 发布