蒙层用的挺多的,有些东西需要设置也挺繁琐的,封装成一个小方法以供下次方便使用。
(function () {
function Init (options) {
this.bodyEl = document.body;
this.tops = 0;
this.state = options.state || 'hide';
this.cartoon = options.cartoon || 'fade';
this.parent = options.parent;
this.bindEvent ();
}
Init.prototype.bindEvent = function () {
if (this.state === 'hide') {
if (this.cartoon === 'fade') {
this.parent.fadeOut();
} else {
this.parent.slideUp();
}
//蒙层取消,让页面可以滑动恢复正常
this.bodyEl.style.position = '';
this.bodyEl.style.top = '';
window.scrollTo(0, this.tops);
} else {
if (this.cartoon === 'fade') {
this.parent.fadeIn();
} else {
this.parent.slideDown();
}
//蒙层滑动防止页面跟着滑动
this.tops = window.scrollY;
this.bodyEl.style.position = 'fixed';
this.bodyEl.style.left = '0px';
this.bodyEl.style.right = '0px';
this.bodyEl.style.top = -this.tops + 'px';
}
}
$.fn.extend({
mark: function (options) {
options.parent = this;
new Init (options);
}
})
}())
调用
$('.mark-box').mark({
state: 'hide', //或者‘show’
cartoon: 'fade' //或者'slide'
})
一般我用的样式如下
.mark-box {
display: none;
position: fixed;
top: 0;
left: 0;
background-color: rgba(0, 0, 0, 0.1);
width: 100%;
height: 100%;
z-index: 100000;
}
.content-box {
background-color: rgba(255, 255, 255, 0.9);
width: 80%;
height: 100px;
position: absolute;
left: 50%;
top: 50%;
transform: translateY(-50%) translateX(-50%);
box-shadow: 0px 7px 8px -5px #fff;
border-radius:8px;
}
事件
$('.mark-box').click(function () {
$('.mark-box').mark({
state: 'hide',
cartoon: 'fade'
})
isMark = !isMark;
});
$('.content-box').click(function (e) {
e.stopPropagation();
});