拖拽的基本原理:
当mousedown时记下鼠标点击位置离拖拽容器左边沿的距离和上边沿的距离,即tmpX,tmpY;mousemove时通过定位拖拽容器的style.left/style.top,使拖拽容器进行移动,定位到哪里则由刚刚的tmpX/tmpY和当前鼠标所在位置计算得出;mouseup时,结束移动。
设置拖拽容器可拖拽的范围,若未设置,则默认为当前窗口可视范围。Note:在设置范围的时候使用Math.max/min来处理,而不是用If语句判断,用后者的话会导致快速拖拽时未达到容许范围边沿即停止的状况。
Html代码:
<div id="box">
drag me
</div>
Css代码:
#box{position:absolute; left:100px; top:100px; padding:5px; background:#f0f3f9; font-size:12px; -moz-box-shadow:2px 2px 4px #666666; -webkit-box-shadow:2px 2px 4px #666666;width: 100px;height: 100px;}
JavaScript代码:
var params = {
left: 100,
top: 100,
currentX: 0,
currentY: 0,
flag: false
};
var obox = document.getElementById("box");
Dragme(obox);
//拖拽的实现
function Dragme(boxdrag){
//o是移动对象
boxdrag.onmousedown = function(event){
params.flag = true;
var e = event;
params.currentX = e.clientX;
params.currentY = e.clientY;
};
document.onmouseup = function(){
params.flag = false;
params.left = boxdrag.style.left;
params.top = boxdrag.style.top;
};
document.onmousemove = function(event){
var e = event ? event: window.event;
if(params.flag){
var nowX = e.clientX, nowY = e.clientY;
var disX = nowX - params.currentX, disY = nowY - params.currentY;
boxdrag.style.left = parseInt(params.left) + disX + "px";
boxdrag.style.top = parseInt(params.top) + disY + "px";
}
}
};