我想做一个
modal
弹出窗口, 在弹出时将页面的滚动条隐藏, 关闭弹窗时再显示滚动条,现在做法是, 弹出时为
body
设置overflow: hidden
, 可是页面就会滚动到最顶端.请问, 如何在添加
overflow: hidden
时保持页面不滚动到顶端.
我想做一个modal
弹出窗口, 在弹出时将页面的滚动条隐藏, 关闭弹窗时再显示滚动条,
现在做法是, 弹出时为body
设置 overflow: hidden
, 可是页面就会滚动到最顶端.
请问, 如何在添加overflow: hidden
时保持页面不滚动到顶端.
设置弹出组件的位置,当body发生滚动时,overlay position的相对位置也将发生滚动,position:absolute不是相对于窗口而是相对于position属性为relative或absolute或fixed的最近的祖先元素
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<style>
.scroll-item{
width: 100px;
height: 50px;
background-color: #0c82df;
margin-bottom: 20px;
margin-left: 10px;
}
.last-item{
background-color: red;
cursor: pointer;
}
.over-lay{
width: 100%;
height: 100%;
background-color: rgba(204,204,204,.8);
border: 1px solid #cccccc;
border-radius: 5px;
position: absolute;
left:30px;
top:30px;
display: none;
}
body{
overflow-y: auto;
overflow-x: hidden;
margin: 0px;
padding: 0px;
}
.over-lay.show{
display: flex;
justify-content: center;
align-items: center;
}
.close{
width: 100px;
height: 50px;
background-color: #ffffff;
border: 1px solid #cccccc;
display: flex;
justify-content: center;
align-items: center;
}
</style>
</head>
<body>
<div class="scroll-item"></div>
<div class="scroll-item"></div>
<div class="scroll-item"></div>
<div class="scroll-item"></div>
<div class="scroll-item"></div>
<div class="scroll-item"></div>
<div class="scroll-item"></div>
<div class="scroll-item"></div>
<div class="scroll-item"></div>
<div class="scroll-item"></div>
<div class="scroll-item"></div>
<div class="scroll-item"></div>
<div class="scroll-item last-item">最后一个</div>
<div class="over-lay">
<div class="close">Close</div>
</div>
<script>
var scrolldiv_lastItem=document.getElementsByClassName("scroll-item last-item")[0];
var body=document.getElementsByTagName("body")[0];
var overLay=document.getElementsByClassName("over-lay")[0];
var closeButton=document.getElementsByClassName("close")[0];
scrolldiv_lastItem.addEventListener("click",function(){
overLay.setAttribute("class","over-lay show");
//设置弹出组件的位置,当body发生滚动时,overlay position的相对位置也将发生滚动
//position:absolute不是相对于窗口而是相对于position属性为relative或absolute或fixed的最近的祖先元素
var bodyBoundingRect=body.getBoundingClientRect();
overLay.setAttribute("style","left:"+(bodyBoundingRect.left)+"px;"+"top:"+(Math.abs(bodyBoundingRect.top))+"px;");
body.setAttribute("style","overflow:hidden;");
},false);
closeButton.addEventListener("click",function(){
body.setAttribute("style","");
overLay.setAttribute("class","over-lay");
overLay.setAttribute("style","");
});
</script>
</body>
</html>
3 回答1.4k 阅读✓ 已解决
4 回答1.4k 阅读✓ 已解决
2 回答1k 阅读✓ 已解决
2 回答1.6k 阅读✓ 已解决
2 回答1.5k 阅读✓ 已解决
4 回答1.5k 阅读
2 回答977 阅读✓ 已解决
scrollTop
记录滚动位置,
overflow: hidden的时候, 同时赋值为记录的位置数值.
//但是我以当前页面测试 overflow: hidden的时候并不会移动到顶部.
body随便划, 当关闭窗口的时候, 给body.scrollTop赋回记录的值即可.
监听滑动事件, 每次滑动, 都给body.scrollTop 赋值为记录的值.