最近在项目开发中,有一个需求,需要有一个覆盖层,覆盖整改页面,同时要有个始终居中的<div>元素,里面提示相应信息,不管是是否滚动。
(1)覆盖层处理。弹出层使用<div>,样式如下:
<style type="text/css">
#shadowDiv {
display: none;
width: 100%;
height: 100%;
position: absolute;
top: 0px ;
left : 0px;
background-color: #FFF;
filter: alpha(opacity = 70);
opacity: 0.7;
z-index: 655
}
</style>
使用的是半透明的设置,同时需要有个z-index,因为后面需要的居中的div层需要位于此覆盖层之上。
页面新增一个<div>元素:
<div id="shadowDiv"></div>
使用页面初始加载函数,页面加载后便展示该覆盖层:
<script >
window.οnlοad=function test(){
var d = $("#shadowDiv");
d.css("display","block");
d.css("height",document.body.scrollHeight+"px");
}
</script>
设置div的高度为document.body.scrollHeight,是因为该页面有滚动条,scrollHeight是获取当前文档的总高度,该高度是大于当前屏幕高度的。此外还要加上“px”,表示单位,没加单位,便没有该效果。效果如下所示:
(2).弹出div始终居中:
页面新增一个div:
div id="testDiv" style="z-index: 666;position: absolute;background-color: green;height:50%;width:100%">
弹出层测试
</div>
该div的z-index为666,大于覆盖层的z-index.便能浮动在覆盖层上面,js函数处理如下:
$(document).ready(function(){
//alert("hello");
var obj=$("#testDiv");
var screenWidth = $(window).width(), screenHeight = $(window).height(); //当前浏览器窗口的 宽高
var scrolltop = $(document).scrollTop();//获取当前窗口距离页面顶部高度
var objLeft = (screenWidth - obj.width())/2 ;
var objTop = (screenHeight - obj.height())/2 + scrolltop;
obj.css({left: objLeft + 'px', top: objTop + 'px'});
//浏览器窗口大小改变时
$(window).resize(function() {
screenWidth = $(window).width();
screenHeight = $(window).height();
scrolltop = $(document).scrollTop();
objLeft = (screenWidth - obj.width())/2 ;
objTop = (screenHeight - obj.height())/2 + scrolltop;
obj.css({left: objLeft + 'px', top: objTop + 'px'});
});
//浏览器有滚动条时的操作、
$(window).scroll(function() {
screenWidth = $(window).width();
screenHeight = $(window).height();
scrolltop = $(document).scrollTop();
objLeft = (screenWidth - obj.width())/2 ;
objTop = (screenHeight - obj.height())/2 + scrolltop;
obj.css({left: objLeft + 'px', top: objTop + 'px'});
});
});
这样不管浏览器窗口大小是否改变,或者是否滚动滚动条,都是始终在页面中间:
附:
各种页面高度:
网页可见区域宽:document.body.clientWidth
网页可见区域高:document.body.clientHeight
网页可见区域宽:document.body.offsetWidth (包括边线的宽)
网页可见区域高:document.body.offsetHeight (包括边线的宽)
网页正文全文宽:document.body.scrollWidth
网页正文全文高:document.body.scrollHeight
网页被卷去的高:document.body.scrollTop
网页被卷去的左:document.body.scrollLeft
网页正文部分上:window.screenTop
网页正文部分左:window.screenLeft
屏幕分辨率的高:window.screen.height
屏幕分辨率的宽:window.screen.width
屏幕可用工作区高度:window.screen.availHeight
屏幕可用工作区宽度:window.screen.availWidth
HTML精确定位:scrollLeft,scrollWidth,clientWidth,offsetWidth
scrollHeight: 获取对象的滚动高度。
scrollLeft:设置或获取位于对象左边界和窗口中目前可见内容的最左端之间的距离
scrollTop:设置或获取位于对象最顶端和窗口中可见内容的最顶端之间的距离
scrollWidth:获取对象的滚动宽度
offsetHeight:获取对象相对于版面或由父坐标 offsetParent 属性指定的父坐标的高度
offsetLeft:获取对象相对于版面或由 offsetParent 属性指定的父坐标的计算左侧位置
offsetTop:获取对象相对于版面或由 offsetTop 属性指定的父坐标的计算顶端位置
event.clientX 相对文档的水平座标
event.clientY 相对文档的垂直座标
event.offsetX 相对容器的水平坐标
event.offsetY 相对容器的垂直坐标
document.documentElement.scrollTop 垂直方向滚动的值
event.clientX+document.documentElement.scrollTop 相对文档的水平座标+垂直方向滚动的量