#給拖拽組件配置不同參數
解決參數順序的問題,可以通過傳遞一個對象來解決
```
function show(opt){
}
show({
id: 'div1',
toDown: function(){},
toUp: function(){}
});
```
利用對象復制就可以解決參數報錯的問題
```
var a = {
name: '小明'
};
var b = {
name: '小強'
};
extend(b, a);
alert(b.name); // 小明 有配置參數則使用配置參數
function extend(obj1, obj2) {
for (var attr in obj2) {
obj1[attr] = obj2[attr];
}
}
```
```
var a = { // 配置參數
// name: '小明'
};
var b = { // 默認參數
name: '小強'
};
extend(b, a);
alert(b.name); // 小強 沒有配置參數則使用默認參數
function extend(obj1, obj2) {
for (var attr in obj2) {
obj1[attr] = obj2[attr];
}
}
```
給拖拽組件配置不同參數
```
<style>
#div1, #div2, #div3, #div4{
width: 100px;
height: 100px;
position: absolute;
}
#div1{
background: #c40000;
}
#div2{
background: green;
left: 100px;
}
#div3{
background: brown;
left: 200px;
}
#div4{
background: blue;
left: 300px;
}
</style>
<script>
window.onload = function () {
var d1 = new Drag();
d1.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 = '課堂';
}
});
var d4 = new Drag();
d4.init({ // 配置參數
id: 'div4',
toUp: function () {
document.title = 'byebye';
}
});
};
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 (e) {
var e = e || window.event;
_this.fnDown(e);
_this.settings.toDown(); // 調用的時候是調用的默認參數
document.onmousemove = function (e) {
var e = e || window.event;
_this.fnMove(e);
};
document.onmouseup = function () {
_this.fnUp();
_this.settings.toUp(); // 調用的時候是調用的默認參數
};
return false;
};
};
Drag.prototype.fnDown = function (e) {
this.disX = e.clientX - this.obj.offsetLeft;
this.disY = e.clientY - this.obj.offsetTop;
};
Drag.prototype.fnMove = function (e) {
this.obj.style.left = e.clientX - this.disX + 'px';
this.obj.style.top = e.clientY - this.disY + 'px';
};
Drag.prototype.fnUp = function () {
document.onmousemove = null;
document.onmouseup = null;
};
function extend(obj1, obj2) {
for (var attr in obj2) {
obj1[attr] = obj2[attr];
}
}
</script>
<div id="div1"></div>
<div id="div2"></div>
<div id="div3"></div>
<div id="div4"></div>
```
- 01 JS面向對象及組件開發
- 02 傳統的過程式編寫選項卡
- 03 用面向對象封裝通用選項卡
- 04 控制多個選項卡自動播放
- 05 用面向對象編寫拖拽
- 06 JS面向對象及組件開發
- 07 hasOwnProperty和constructor的使用
- 08 instanceof運算符的使用
- 09 利用toString做類型判斷
- 10 什么是面向對象的繼承
- 11 面向對象之拷貝繼承
- 12 編寫繼承的拖拽
- 13 繼承的其他形式之類式繼承
- 14 繼承的其他形式之原型繼承
- 15 組件開發是什么
- 16 給拖拽組件配置不同參數
- 17 封裝彈框組件
- 18 使用對象標記已彈出彈框
- 19 復雜組件開發之自定義事件
- 20 原生JS實現自定義事件
- 21 自定義事件實例
- 22 基于JQ的選項卡組件開發