JS拖拽效果,代码精干,通俗易懂!
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title></title>
<style>
div{
margin-top: 10px;
width: 200px;
height: 150px;
background: #dadada;
position: absolute;
cursor:move;
}
</style>
</head>
<body>
<div id="div" ></div>
<script>
var drag=false;
var x, y,movex,movey;
var movediv =document.getElementById(‘div‘);
movediv.onmousedown=function(){
drag=false;
x = window.event.clientX; /*当前鼠标坐标*/
y =window.event.clientY;
movex = movediv.offsetLeft; /*当前元素坐标*/
movey =movediv.offsetTop
}
document.onmousemove=function(){
if(drag) return false;
movediv.style.top= movey + window.event.clientY -y +‘px‘;
movediv.style.left= movex + window.event.clientX -x +‘px‘;
}
document.onmouseup=function(){drag=true}
</script>
</body>
</html>
郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。