基本拖拽
by 孙 超
HTML
<div id="box" class="box">
这里是内容
</div>
<div>
这里是底部文字内容这里是底部文字内容这里是底部文字内容这里是底部文字内容这里是底部文字内容这里是底部文字内容这里是底部文字内容这里是底部文字内容这里是底部文字内容这里是底部文字内容这里是底部文字内容这里是底部文字内容这里是底部文字内容这里是底部文字内容这里是底部文字内容这里是底部文字内容这里是底部文字内容这里是底部文字内容这里是底部文字内容这里是底部文字内容这里是底部文字内容这里是底部文字内容这里是底部文字内容这里是底部
</div>
CSS
*{
margin:0;
padding:0;
}
.box{
position:absolute;
width:100px;
height:100px;
background-color:red;
}
JavaScript
window.onload=function() {
var oBox = document.getElementById("box");
oBox.onmousedown = function(ev){
// 获取鼠标在小块内部的位置(距离)
var oEvent = ev || event;
var disX = oEvent.clientX - this.offsetLeft;
var disY = oEvent.clientY - this.offsetTop;
document.onmousemove = function(ev){
var oEvent = ev || event;
var l = oEvent.clientX - disX;
var t = oEvent.clientY - disY;
oBox.style.left = l + "px";
oBox.style.top = t + "px";
};
document.onmouseup = function(){
document.onmousemove = document.onmouseup = null;
if(oBox.setCapture){
oBox.releaseCapture();
}
};
// 避免选中文本
if(oBox.setCapture){
oBox.setCapture();
}
return false;
};
};