Rumah > Artikel > hujung hadapan web > 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; } } }
相关推荐:
HTML5讲解之拖拽事件dragstart、drag和dragend
Atas ialah kandungan terperinci js实现拖拽事件的方法实例. Untuk maklumat lanjut, sila ikut artikel berkaitan lain di laman web China PHP!