Last active
August 29, 2015 14:16
-
-
Save think2011/1cf936be56d11431edc0 to your computer and use it in GitHub Desktop.
元素切换机
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* 切换元素显示状态 | |
* | |
* @param btns {object} 定义要切换的元素组 | |
* @constructor | |
* @example | |
var actions = new ChangeState({ a: ['#box', '#box2'], b: ['.box3']); | |
actions.a(); | |
*/ | |
function ChangeState(btns) { | |
this._btns = btns; | |
this._init(btns); | |
} | |
ChangeState.prototype = { | |
constructor: ChangeState, | |
_init: function (btns) { | |
var that = this, _all = []; | |
(Object.keys(btns)).forEach(function (key) { | |
btns[key].forEach(function (el, index) { | |
_all.push(btns[key][index] = document.querySelector(el)); | |
}); | |
that[key] = function () { | |
that._change(key); | |
} | |
}); | |
btns.all = _all; | |
}, | |
_setDisplay: function (el, value) { | |
el.style.display = value; | |
}, | |
_allHide: function () { | |
var that = this; | |
that._btns.all.forEach(function (v) { | |
that._setDisplay(v, 'none'); | |
}); | |
return that._btns; | |
}, | |
/** | |
* 切换元素组 | |
* @param key {string} 在 this.btns 中定义的key | |
*/ | |
_change: function (key) { | |
var that = this; | |
that._allHide()[key].forEach(function (v) { | |
that._setDisplay(v, 'block'); | |
}); | |
} | |
}; | |
// 例子 | |
var actions = new ChangeState({ | |
start: ['#box', '#box2'], | |
pause: ['#box3'], | |
stop: ['.box4'] | |
}); | |
actions.start(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment