您的位置:首页 > 其它

拖拽原理

2016-12-02 20:01 483 查看
拖拽原理

1.鼠标按下+鼠标移动  =  拖拽      事件  onmousedown +  onmousemove  

2.鼠标松开  =  无拖拽                  停止拖拽  onmouseup

3.鼠标偏移  =   拖拽距离 

<!DOCTYPE html>
<html>
<head lang="en">
<meta charset="UTF-8">
<title></title>
<style>
.box{
width:100px;
height:100px;
background-color:greenyellow;
}
</style>
</head>
<body>
<div class="box"></div>
<script>
var box=document.getElementsByTagName("div");
drag(box[0]);
function drag(elem){
var oldX,oldY,newX,newY;
elem.onmousedown=function(e){
//相对定位的拖拽div
this.style.position="relative";
if(!this.style.left && !this.style.top){
//第一次设置left、top为0
this.style.left = 0;
this.style.top = 0;
}
var oldX= e.clientX;
var oldY= e.clientY;
document.onmousemove=function(e){
newX= e.clientX;
newY= e.clientY;
elem.style.left=parseInt(elem.style.left)+newX-oldX+"px";
elem.style.top=parseInt(elem.style.top)+newY-oldY+"px";
oldX=newX;
oldY=newY;
}
document.onmouseup=function(){
document.onmousemove=null;
document.onmousedown=null;
}

}

}
</script>
</body>
</html>
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: