js 面向对象组件开发

组件开发: 节生代码量,易复用。
组件开发遇到的两个问题

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;

}

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值