首页 > 代码库 > 如何拖动DOM元素
如何拖动DOM元素
.divblok {
width:200px;
height:100px;
position:absolute;
left:20px;
top:20px;
}
<div id="dragdiv" draggable="true" class="divblok">移动 </div>
window.onload=function(){
var dragdiv = document.querySelector(‘#dragdiv‘);
var x, y;
dragdiv.addEventListener(‘dragstart‘, function (e) {
e.dataTransfer.setData("text", ‘‘);
x = e.offsetX || e.layerX;
y = e.offsetY || e.layerY;
return true;
}, false);
document.addEventListener(‘dragover‘, function (e) {
e.preventDefault()|| e.stopPropagation();
}, false);
document.addEventListener(‘drop‘, function (e) {
dragdiv.style.left = (e.pageX - x) + ‘px‘;
dragdiv.style.top = (e.pageY - y) + ‘px‘;
e.preventDefault() || e.stopPropagation();
}, false);
}
如何拖动DOM元素