js元素完美拖拽效果
阿新 • • 發佈:2019-02-19
*{margin:0;padding:0;}
#div1{width:100px;height:100px;background:red;position:relative;}
window.onload=function(){
var div=document.getElementByIdx_x("div1"); //獲得被移動元素的id
var disX=0,X=0;disY=0;
div.onmousedown = function(ev){
var oEvent= ev || window.event;
disX=oEvent.clientX; //滑鼠點選位置的橫座標
disY=oEvent.clientY; //滑鼠點選位置的縱座標
disLeft=div.offsetLeft; //div塊的左邊距
disTop=div.offsetTop; //div塊的上邊距
document.onmousemove = function(ev){
var oEvent= ev || window.event;
X=oEvent.clientX-disX;
Y=oEvent.clientY-disY;
div.style.left =disLeft+X+"px";
div.style.top =disTop+Y+"px";
}
div.onmouseup=function(){
div.onmouseup=null;
document.onmousemove=null;
return false;
}
}
}
#div1{width:100px;height:100px;background:red;position:relative;}
window.onload=function(){
var div=document.getElementByIdx_x("div1"); //獲得被移動元素的id
var disX=0,X=0;disY=0;
div.onmousedown = function(ev){
var oEvent= ev || window.event;
disX=oEvent.clientX; //滑鼠點選位置的橫座標
disY=oEvent.clientY; //滑鼠點選位置的縱座標
disLeft=div.offsetLeft; //div塊的左邊距
disTop=div.offsetTop; //div塊的上邊距
document.onmousemove = function(ev){
var oEvent= ev || window.event;
X=oEvent.clientX-disX;
Y=oEvent.clientY-disY;
div.style.left =disLeft+X+"px";
div.style.top =disTop+Y+"px";
}
div.onmouseup=function(){
div.onmouseup=null;
document.onmousemove=null;
return false;
}
}
}