显示隐藏模块实现的几种方式
网页结构:
<style>
body {
width: 400px;
margin: 0 auto;
}
.btn {
width:50%;
height: 30px;
}
#box {
width: 200px;
height:100px;
background-color: red;
overflow: hidden;
}
</style>
<button id="btn-show" class="btn">显示</button>
<button id="btn-hide" class="btn">隐藏</button>
<div id="box" class=""> </div>
1、传统jQuery代码:
//函数的定义
var silent = {
show: function ($elem) {
$elem.html('<p>我要显示了</p>');
$elem.show();
setTimeout(function () {
$elem.html($elem.html() + '<p>我已经显示了</p>');
}, 1000)
},
hide: function ($elem) {
$elem.hide();
}
};
//函数的执行
var $box = $('#box');
$('#btn-show').on('click', function () {
silent.show($box);
});
$('#btn-hide').on('click', function () {
silent.hide($box);
});
2、通过回调函数实现解耦
var silent = {
show: function ($elem, showCallback, shownCallback) {
if (typeof showCallback === 'function') showCallback();
$elem.show();
if (typeof shownCallback === 'function') shownCallback();
},
hide: function ($elem) {
$elem.hide();
}
};
var $box = $('#box');
$('#btn-show').on('click', function () {
silent.show($box, function () {
$box.html('<p>我要显示了</p>');
}, function () {
setTimeout(function () {
$box.html($box.html() + '<p>我已经显示了</p>');
}, 1000)
});
});
$('#btn-hide').on('click', function () {
silent.hide($box);
});
3、发布订阅模式
发布订阅模式可以让不同的人增加新的功能而互不影响。
var silent = {
inti:function($elem){
if($elem.is(':hidden')){
$elem.data('status','hidden');
}else{
$elem.data('status','shown');
}
},
show: function ($elem) {
if ($elem.data('status') === 'show') return;
if ($elem.data('status') === 'shown') return;
$elem.data('status','show').trigger('show'); //绑定状态,阻止连续点击带来的资源浪费
$elem.show();
$elem.data('status','shown').trigger('shown');
},
hide: function ($elem) {
$elem.data('status','hide').trigger('hide');
$elem.hide();
$elem.data('status','hidden').trigger('hidden');
}
};
//触发事件
var $box = $('#box');
silent.inti($box);
$('#btn-show').on('click',function () {
silent.show($box);
});
//小A同学对事件绑定的时间
$box.on('show shown hide hidden',function(e){
if(e.type === 'show'){
$box.html('<p>我要显示了</p>');
}else if(e.type === 'shown'){
setTimeout(function () {
$box.html($box.html() + '<p>我已经显示了</p>');
}, 1000);
}
});
$('#btn-hide').on('click', function () {
silent.hide($box);
});