自从上次写过拖拽就忘了怎么实现。今天又研究了半天,终于搞懂了。
首先,被拖拽的元素一定要设置position:absolute,今天就是忘了这一点,频频出错,不得要领。
其次,拖拽分三个步骤:
1.点击元素,即onmousedown;
2.移动,即onmousemove;
3.鼠标弹起,即onmouseup;
总结代码如下:
pox.onmousedown = function(e){
var e = e || window.event;
var diffX = e.clientX - pox.offsetLeft;
var diffY = e.clientY - pox.offsetTop;
document.onmousemove = function(e){
var e = e || window.event;
pox.style.left = e.clientX - diffX + 'px';
pox.style.top = e.clientY - diffY + 'px';
}
document.onmouseup = function(){
document.onmousemove = null;
document.onmouseup = null;
}
}