组件开发遇到的两个问题:
1: 参数不写的话,会报错
--- extend() 对象的复制,避免参数报错
--a配置参数 b:默认参数 有配置走配置,没有配置走默认。注意:a,b的key值要相同,否则就不能进行值的覆盖。
var a = {
name: 'anikin'
};
var b = {
name: 'jack'
}
extend( a , b);
alert( a.name ); // jack
2:如果参数比较多,有的参数不写的话,参数顺序对应不上的问题;---json解决
extend 对象的复制函数:
function extend(obj1,obj2){拖拽完整案例:
for(var attr in obj2){
obj1[attr] = obj2[attr];
}
}
window.onload = function(){
var d1 = new Drag();
d1.init({
id: 'div1',
toDown: function(){
document.body.style.backgroundColor = 'green';
},
toUp: function(){
document.body.style.backgroundColor = 'yellow';
}
});
var d2 = new Drag();
d2.init({
id: 'div2',
toUp: function(){
document.body.style.backgroundColor = 'yellow';
}
});
var d3 = new Drag();
d3.init({
id: 'div3',
toDown: function(){
document.title = 'hellow';
}
});
};
function Drag(){
this.obj = null;
this.disx = 0;
this.disy = 0;
// 设置配置参数
this.setting = {
toDown: function(){},
toUp: function(){}
};
}
Drag.prototype.init = function( opt ){
var This = this;
this.obj = document.getElementById( opt.id );
extend( this.setting, opt );
this.obj.onmousedown = function(ev){
var ev = ev || window.event;
This.fnMouseDown(ev);
This.setting.toDown();
document.onmousemove = function(ev){
This.fnMouseMove( ev );
}
document.onmouseup = function(){
This.fnMouseUp();
This.setting.toUp();
}
return false;
};
}
Drag.prototype.fnMouseDown = function(ev){
this.disx = ev.clientX - this.obj.offsetLeft;
this.disy = ev.clientY - this.obj.offsetTop;
}
Drag.prototype.fnMouseMove = function(ev){
this.obj.style.left = ev.clientX - this.disx + 'px';
this.obj.style.top = ev.clientY - this.disy + 'px';
}
Drag.prototype.fnMouseUp = function(){
document.onmousemove = null;
document.onmouseup = null;
}