JavaScript 拖拽效果-动画
鼠标按下 onmousedown,onmousedown 里边鼠标移动 onmousemove,鼠标释放 onmouseup
js
var oDiv = document.getElementById('box');
var disX = disY = 0;
oDiv.onmousedown = function(ev){
var ev = ev || event;
disX = ev.offsetX;
disY = ev.offsetY;
document.onmousemove = function(ev){
var ev = ev || event;
var l = ev.clientX - disX;
var t = ev.clientY - disY;
// 边界限定
if(l <= 0){
l = 0;
}else if(l >= document.documentElement.clientWidth - oDiv.offsetWidth){
l = document.documentElement.clientWidth - oDiv.offsetWidth;
}
if(t <= 0){
t = 0;
}else if(t >= document.documentElement.clientHeight - oDiv.offsetHeight){
t = document.documentElement.clientHeight - oDiv.offsetHeight;
}
// 吸附效果
/* if(l <= 100){
l = 0;
}else if(l >= document.documentElement.clientWidth - oDiv.offsetWidth - 100){
l = document.documentElement.clientWidth - oDiv.offsetWidth;
}
if(t <= 0){
t = 0;
}else if(t >= document.documentElement.clientHeight - oDiv.offsetHeight){
t = document.documentElement.clientHeight - oDiv.offsetHeight;
} */
oDiv.style.left = l + 'px';
oDiv.style.top = t + 'px';
}
document.onmouseup = function(){
this.onmousemove = null;
this.onmouseup = null;
}
}