1. 程式人生 > >面向對象組件開發-拖拽

面向對象組件開發-拖拽

get sed tin eas cli tel back doc capture

<div id="div1"></div>
<div id="div2"></div>
<div id="div3"></div>

CSS

#div1{
	width: 100px;
	height: 100px;
	background: red;
	position: absolute;
}
#div2{
	width: 100px;
	height: 100px;
	background: yellow;
	position: absolute;
	left: 100px;
}
#div3{
	width: 100px;
	height: 100px;
	background: blue;
	position: absolute;
	left: 200px;
}

JS

/*
組件開發:多組對象,像兄弟之間的關系(代碼復用的一種形式)


 * */
//拖拽
function Drag(){
	this.obj=null;
    this.disX=0;
    this.disY=0;
    
    this.settings={ //默認參數
    	toDown:function(){},
    	toUp:function(){}
    };
}
Drag.prototype.init=function(opt){
    var This=this;
   	this.obj=document.getElementById(opt.id);
   	extend(this.settings,opt);
    this.obj.onmousedown=function(ev){
        var ev=ev||window.event;
        This.fnDown(ev);
        
        This.settings.toDown();
        document.onmousemove=function(ev){
	        var ev=ev||window.event; 
	        This.fnMove(ev);
	    };
	    document.onmouseup=function(ev){
	        var ev=ev||window.event; 
	        This.fnUp(ev);
	        
	        This.settings.toUp();
	    };
        //清除默認事件
        return false;
    }
}
Drag.prototype.fnDown=function(ev){
    var This=this;
    this.disX=ev.clientX-this.obj.offsetLeft;
    this.disY=ev.clientY-this.obj.offsetTop;
     
    //設置全局捕獲
    //所有的onmousemove或者onmouseup都被oImg截獲,然後作用在oImg身上
    if(this.obj.setCapture){
        this.obj.setCapture();
    }
     
    document.onmousemove=function(ev){
        var ev=ev||window.event; 
        This.fnMove(ev);
    };
    document.onmouseup=function(ev){
        var ev=ev||window.event; 
        This.fnUp(ev);
    };
}
Drag.prototype.fnMove=function(ev){
    var L=ev.clientX-this.disX;
    var T=ev.clientY-this.disY;
     
    this.obj.style.left=L+‘px‘;
    this.obj.style.top=T+‘px‘;
}
Drag.prototype.fnUp=function(){
    document.onmousemove=null;
    //釋放全局捕獲
    if(this.obj.releaseCapture){
        this.obj.releaseCapture();
    }
}
var dl=new Drag();
dl.init({ //配置參數
	id:‘div1‘
});

var d2=new Drag();
d2.init({ //配置參數
	id:‘div2‘,
	toDown:function(){
		document.title=‘hello‘;
	}
});

var d3=new Drag();
d3.init({ //配置參數
	id:‘div3‘,
	toDown:function(){
		document.title=‘你好‘;
	},
	toUp:function(){
		document.title=‘BeyBey‘;
	}
});

function extend(obj1,obj2){
    for (var attr in obj2) {
        obj1[attr]=obj2[attr];
    }
}

  

面向對象組件開發-拖拽