<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
##以上是js實作拖曳事件的方法實例的詳細內容。更多資訊請關注PHP中文網其他相關文章!