这里介绍两种实现元素拖拽的方法
<style>
*{margin:0;padding:0}
.box{position:absolute;
top:0;
left:0;
width:300px;
height:300px;
background-color: chocolate;
}
</style>
<body>
<div class="box"></div>
先定义一个元素
方法1
<script>
let box=document.getElementsByClassName("box")[0];
//鼠标按下事件
box.onmousedown=function(e){//e为事件源
let Top=box.offsetTop,//获取元素的top值
Left=box.offsetLeft,//获取元素的left值
X=e.clientX,//获取鼠标点击时的位置
Y=e.clientY;//获取鼠标点击时的位置
//鼠标移动事件
document.onmousemove=function(e){
box.style.top=e.clientY-Y+Top+"px";
box.style.left=e.clientX-X+Left+"px"
}
}
//鼠标松开事件
document.onmouseup=function(){
document.onmousemove=null;
}
方法2
<div class"box" draggable="true"></div>
<script>
let box=document.getElementsByClassName("box")[0];
box.ondragend=function(e){
box.style.cssText=`left:${e.clientX-0}px;top:${e.clientY-0}px;`
}
</script>
这是h5的拖拽。不过本人觉得原生js的用起来比较舒服,还有,此方法不兼容火狐,只能在谷歌下用