我创建了一个模态。一切顺利。当内容很多时,会出现一个垂直滚动条。
问题是如果正文页面和模态有很多内容,那么会有两个垂直滚动条。
这是一个例子:
function showModal() {
// Hide Body Scrollbar
// document.body.style.overflow = "hidden";
document.getElementById("myModal").style.display="block";
// When the user clicks anywhere outside of the modal, close it
var modal = document.getElementById("myModal");
window.onclick = function(event) {
if (event.target == modal) {
//modal.style.display = "none";
closeModal();
}
}
}
function closeModal() {
// Show Body Scrollbar
// document.body.style.overflow = "visible";
document.getElementById("myModal").style.display="none";
}
.modal {
display: none;
position: fixed;
z-index: 2;
top: 0;
left: 0;
width: 100%;
height: 100%;
overflow: auto;
background-color: rgb(0,0,0);
background-color: rgba(0,0,0,0.4);
}
.modalContent {
border-radius: 10px;
background-color: #fefefe;
margin: 10% auto; /* 15% from the top and centered */
padding: 0;
border: 1px solid #888;
width: 50%; /* Could be more or less, depending on screen size */
overflow: hidden;
}
.modal .modalHeader {
font-family: 'Ubuntu', Arial;
font-weight: bold;
padding: 10px;
margin: 0;
}
.modal .modalHeader span {
color: #7788C9;
letter-spacing: 4px;
}
.modal .modalHeader .close {
color: #000;
float: right;
padding: 0 10px;
}
.clear-close{clear:right;display: block;}
.modal .modalBody {
background-color: #FFF;
border-top: 1px solid #ccc;
border-bottom: 1px solid #ccc;
color: #000;
position: static;
padding: 10px;
margin: 0;
}
.modal .modalFooter {
padding: 10px;
margin: 0;
text-align: right;
}
<center>
<h1>Modal</h1>
<button onClick="showModal()">
Show Modal
</button>
<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.
<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.
<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.
<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.
</center>
<div id="myModal" class="modal">
<div id="abc" class="modalContent">
<div class="modalHeader">
<span>Modal</span>
<a href="javascript:void(0)" class="close" onclick="closeModal()">X</a>
</div>
<div class="modalBody clear-close">
This is the modal content.
<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.
<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.
<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.
</div>
<div class="modalFooter">
<a href="javascript:void(0)" onclick="closeModal()">Close</a>
</div>
</div>
</div>
我有我的解决方案,但他们上下起伏:
1)尽量保持模态尽可能短。问题不是每个人都有相同的屏幕尺寸。所以有些人可能会看到2个滚动条。
2)在我的Javascript代码中,document.body.style.overflow
目前被设置为评论。我取消注释。当我单击Show Modal时,它会显示我想要的1个滚动条。但是,当我点击它时,模态后面的内容略微向右移动。 (当网站居中时)
那么,有没有办法在没有主体滚动条的情况下显示模态滚动条,而不会使内容略微向右和向左移动?
注意:我不允许使用jQuery