Skip to content

Instantly share code, notes, and snippets.

@think2011
Last active August 29, 2015 14:16
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save think2011/1cf936be56d11431edc0 to your computer and use it in GitHub Desktop.
Save think2011/1cf936be56d11431edc0 to your computer and use it in GitHub Desktop.
元素切换机
/**
* 切换元素显示状态
*
* @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