jQuery实现遮罩层

时间:2024-04-04 18:05:57

1.1 背景半透明遮罩层样式

  需要一个黑色(当然也可以其他)背景,且须设置为绝对定位,以下是项目中用到的css样式:

/* 半透明的遮罩层 */
#overlay {
background: #000;
filter: alpha(opacity=50); /* IE的透明度 */
opacity: 0.5; /* 透明度 */
display: none;
position: absolute;
top: 0px;
left: 0px;
width: 100%;
height: 100%;
z-index:; /* 此处的图层要大于页面 */
display:none;
}

1.2 jQuery实现遮罩

/* 显示遮罩层 */
function showOverlay() {
$("#overlay").height(pageHeight());
$("#overlay").width(pageWidth()); // fadeTo第一个参数为速度,第二个为透明度
// 多重方式控制透明度,保证兼容性,但也带来修改麻烦的问题
$("#overlay").fadeTo(200, 0.5);
} /* 隐藏覆盖层 */
function hideOverlay() {
$("#overlay").fadeOut(200);
} /* 当前页面高度 */
function pageHeight() {
return document.body.scrollHeight;
} /* 当前页面宽度 */
function pageWidth() {
return document.body.scrollWidth;
}

1.3 提示框

  遮罩的目的无非让人无法操作内容,突出提示框,而提示框可参考上面的制作,z-index比遮罩层更高便可。主要问题是,如何控制提示框在浏览器居中。

/* 定位到页面中心 */
function adjust(id) {
var w = $(id).width();
var h = $(id).height(); var t = scrollY() + (windowHeight()/2) - (h/2);
if(t < 0) t = 0; var l = scrollX() + (windowWidth()/2) - (w/2);
if(l < 0) l = 0; $(id).css({left: l+'px', top: t+'px'});
} //浏览器视口的高度
function windowHeight() {
var de = document.documentElement; return self.innerHeight || (de && de.clientHeight) || document.body.clientHeight;
} //浏览器视口的宽度
function windowWidth() {
var de = document.documentElement; return self.innerWidth || (de && de.clientWidth) || document.body.clientWidth
} /* 浏览器垂直滚动位置 */
function scrollY() {
var de = document.documentElement; return self.pageYOffset || (de && de.scrollTop) || document.body.scrollTop;
} /* 浏览器水平滚动位置 */
function scrollX() {
var de = document.documentElement; return self.pageXOffset || (de && de.scrollLeft) || document.body.scrollLeft;
}