JSドラッグアンドドロップ要素互換IE
3313 ワード
Document
function getpos(ev){
var scrolltop=document.documentElement.scrollTop||document.body.scrollTop;
var scrollleft=document.documentElement.scrollLeft||document.body.scrollLeft;
return {x:ev.clientX+scrollleft,y:ev.clientY+scrolltop}
}
function addEvent(obj,even,fn){ /* */
return obj.addEventListener?obj.addEventListener(even,fn,false):obj.attachEvent("on"+even,fn);
}
function unEvent(obj,even,fn){
return obj.removeEventListener?obj.removeEventListener(even,fn,false):obj.detachEvent("on"+even,fn);
}
window.οnlοad=function(){
var odiv1=document.getElementById("div1");
odiv2=document.getElementById("div2");
disX=0;
disY=0;
addEvent(odiv2,"mousedown",function(ev){
var eventr=ev||event;
pos=getpos(eventr);
disX=pos.x-this.offsetLeft;
disY=pos.y-this.offsetTop;
creatElement=document.createElement("div");
creatElement.className="boxs";
creatElement.style.width=odiv2.offsetWidth-2+"px";
creatElement.style.height=odiv2.offsetHeight-2+"px";
creatElement.style.top=odiv2.offsetTop+"px";
creatElement.style.left=odiv2.offsetLeft+"px";
div1.appendChild(creatElement);
document.οnmοusemοve=function(ev){
var eventr=ev||event;
pos=getpos(eventr);
creatElement.style.left=pos.x-disX+"px";
creatElement.style.top=pos.y-disY+"px";
if(creatElement.offsetTop<0){
creatElement.style.top=0+"px";
}
if(creatElement.offsetLeft<0){
creatElement.style.left=0+"px";
}
if(creatElement.offsetTop>odiv1.offsetHeight-odiv2.offsetHeight){
creatElement.style.top=odiv1.offsetHeight-odiv2.offsetHeight+"px";
}
if(creatElement.offsetLeft>odiv1.offsetWidth-odiv2.offsetWidth){
creatElement.style.left=odiv1.offsetWidth-odiv2.offsetWidth+"px";
}
}
document.οnmοuseup=function(){
odiv2.style.left=creatElement.offsetLeft+"px";
odiv2.style.top=creatElement.offsetTop+"px";
div1.removeChild(creatElement);
unEvent(odiv2,"mousedown");
document.οnmοusemοve=null;
}
return false;
})
}
転載先:https://www.cnblogs.com/junxi/p/5228537.html