pc端拖拽事件
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>pc端拖拽事件</title>
<style type="text/css">
body{
margin: 0;
padding: 0;
}
#div1{
position: absolute;
top: 200px;/*div的y轴*/
left: 150px;/*div的x轴*/
width: 300px;
height: 200px;
background-color: gray;
}
div:hover{
cursor: move;
}
</style>
</head>
<body>
<div id="div1"></div>
</body>
<script type="text/javascript">
var oDiv=document.getElementById('div1');
var disX=0;
var disY=0;
//封装一个函数用于获取鼠标坐标
function getPos(ev){
var scrollTop=document.documentElement.scrollTop||document.body.scrollTop;
var scrollLeft=document.documentElement.scrollLeft||document.body.scrollLeft;
return {x: ev.clientX+scrollLeft, y: ev.clientY+scrollTop};
}
oDiv.onmousedown=function(ev){
var oEvent=ev||window.event;
var pos=getPos(oEvent); //这样就可以获取鼠标坐标,比如pos.x表示鼠标横坐标
disX=pos.x-oDiv.offsetLeft;
disY=pos.y-oDiv.offsetTop;
document.onmousemove=function(ev){
/*由于要防止鼠标滑动太快跑出div,这里应该用document.
因为触发onmousemove时要重新获取鼠标的坐标,不能使用父函数上的pos.x和pos.y,所以必须写var oEvent=ev||event;var pos=getPos(oEvent);*/
var oEvent=ev||window.event;
var pos=getPos(oEvent);
//防止div跑出可视框
var l=pos.x-disX;
var t=pos.y-disY;
if(l<0){
l=0;
}
else if(l>document.documentElement.clientWidth-oDiv.offsetWidth){
l=document.documentElement.clientWidth-oDiv.offsetWidth;
}
if(t<0){
t=0;
}else if(t>document.documentElement.clientHeight-oDiv.offsetHeight){
t=document.documentElement.clientHeight-oDiv.offsetHeight;
}
oDiv.style.left=l+'px';
oDiv.style.top=t+'px';
}
document.onmouseup=function(ev){
document.onmousemove=null; //将move清除
document.onmouseup=null;
}
return false; //火狐的bug,要阻止默认事件
}
</script>
</html>
移动端的拖拽事件
移动端的拖拽事件的思路是当手指点下记录手指的坐标和box的位置。当手指移动的时候记录手指的坐标和box的位置。这样就可以利用两者的差值来计算box怎么移动。具体代码如下:
<!DOCTYPE html>
<html lang="zh">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width,initial-scale=1,minimum-scale=1,maximum-scale=1,user-scalable=no" />
<meta http-equiv="X-UA-Compatible" content="ie=edge" />
<title>Document</title>
<style type="text/css">
#wrap{
width: 100%;
height: 100%;
background-color: #f00;
position: fixed;
top:0;
left: 0;
}
#box{
width: 100px;
height: 100px;
background-color: #0f0;
position: absolute;
top:200px;
left: 200px;
}
</style>
</head>
<body>
<div id="wrap">
<div id="box"></div>
</div>
</body>
<script src="https://code.jquery.com/jquery-3.3.1.min.js"></script>
<script type="text/javascript">
var touchStart_x = null,touchStart_y = null,touchMove_x = null,touchMove_y = null,boxStartX=null,boxStartY=null;
$("#box").on("touchstart",function(e){
touchStart_x = e.targetTouches[0].pageX;
touchStart_y = e.targetTouches[0].pageY;
boxStartX = $("#box").position().left;
boxStartY = $("#box").position().top;
})
$("#box").on("touchmove",function(e){
touchMove_x = e.targetTouches[0].pageX-touchStart_x;
touchMove_y = e.targetTouches[0].pageY-touchStart_y;
$("#box").css({
left:boxStartX + touchMove_x,
top:boxStartY + touchMove_y
})
})
</script>
</html>