要点:在js动态改变css的overflow属性时body和html都要写。
html部分:
<body style="position: relative;">
<div id="background"></div>
<div id="content">
<div class="cont">
<p>内容</p>
<p>内容</p>
<p>内容</p>
<p>内容</p>
<p>内容</p>
<p>内容</p>
<p>内容</p>
<p>内容</p>
<p>内容</p>
<p>内容</p>
</div>
</div>
<button>弹出层</button>
<p style="padding:500px 0">底层内容</p>
</body>
css部分:
<style type="text/css">
#background {
position: absolute;
z-index: 999;
top: 0;
left: 0px;
background: rgb(50, 50, 50);
background: rgba(0, 0, 0, 0.5);
display: none;
}
#content {
position: fixed;
top: 0;
left: 50%;
width: 95%;
z-index: 1000;
padding: 0px 0px 2px 0px;
background: #fff;
border-radius: 5px;
overflow: hidden;
zoom: 1;
box-sizing: border-box;
display: none;
}
.cont {
width: 100%;
height: 100px;
overflow-y: scroll;
}
</style>
Jq部分:
<!--先引用一个jq库-->
<script type="text/javascript" src="js/jquery-2.1.4.min.js"></script>
<script type="text/javascript">
// 弹出层
$(function () {
function conPosition() {
var oBackground = document.getElementById("background");
var dw = $(document).width();
var dh = $(document).height();
oBackground.style.width = dw + 'px';
oBackground.style.height = dh + 'px';
var oContent = document.getElementById("content");
var scrollTop = document.documentElement.scrollTop || document.body.scrollTop;
var l = (document.documentElement.clientWidth - oContent.offsetWidth) / 2;
var t = ((document.documentElement.clientHeight - oContent.offsetHeight) / 2) + scrollTop;
oContent.style.left = l + 'px';
oContent.style.top = t + 'px';
}
$("button").click(function () {
$("#background, #content").show();
$("body").css({
'height': '100%',
'overflow': 'hidden'
});
$("html").css({
'height': '100%',
'overflow': 'hidden'
});
conPosition();
});
$("#background").click(function () {
$("#background, #content").hide();
$("body").css({
'height': '100%',
'overflow': 'visible'
});
$("html").css({
'height': '100%',
'overflow': 'visible'
});
});
//点击黑色背景隐藏弹出层,当然可以绑定在任意一个按钮上
$(window).resize(function () {
conPosition();
});
$(window).scroll(function () {
conPosition();
});
});
</script>