Home >Web Front-end >JS Tutorial >Example of method to implement drag and drop event in js
<body> <p></p></body>
p{ position: absolute; width: 200px; height: 200px; background: #369 }
window.onload = function(){ var op = document.getElementsByTagName("p")[0]; /*鼠标点击的位置距离p左边的距离 */ var disX = 0; /*鼠标点击的位置距离p顶部的距离*/ var disY = 0; op.onmousedown = function(){ var e = e || window.event; disX = e.clientX - op.offsetLeft; disY = e.clientY- op.offsetTop; document.onmousemove = function(e){ var e = e || window.event; // 横轴坐标 var leftX = e.clientX - disX; // 纵轴坐标 var topY =e.clientY - disY; if( leftX < 0 ){ leftX = 0; } /* 获取浏览器视口大小 document.document.documentElement.clientWidth*/ else if( leftX > document.documentElement.clientWidth - op.offsetWidth ){ leftX = document.document.documentElement.clientWidth - op.offsetWidth; } if( topY < 0 ){ topY = 0; } else if( topY > document.documentElement.clientHeight -op.offsetHeight ){ topY = document.documentElement.clientHeight - op.offsetHeight; } op.style.left = leftX + "px"; op.style.top = topY+"px"; } document.onmouseup = function(){ document.onmousemove = null; document.onmouseup = null; } } }
Related recommendations:
JavaScript mouse drag event implementation case
HTML5 explanation of drag events dragstart, drag and dragend
The above is the detailed content of Example of method to implement drag and drop event in js. For more information, please follow other related articles on the PHP Chinese website!