首先,我知道同样的问题已被问过好几次,但我无法让它正常工作。在我正在实现的网站上,我打开一个带有一些信息的弹出窗口,然后阻止 body 的其余部分滚动。我想允许滚动弹出窗口而不是菜单。还要避免在主体上使用“位置:固定”,因为它会将页面移动到顶部。我缺少什么来防止 body 滚动? body 已经具有“溢出:隐藏”的属性。这是我开发的代码:
http://www.produccionsf2f.com/equipo/
HTML:
覆盖 body 的覆盖层:
<div id="scid-overlay" class="x-section scid-transition-eio overlay-open" style="margin: 0px;padding: 0px; background-color: hsla(0, 0%, 1%, 0.69);"><div class="x-container max width" style="margin: 0px auto;padding: 0px;height: 0;">
实际弹出:
<div id="scid-overlay" class="x-section scid-transition-eio overlay-open" style="margin: 0px;padding: 0px; background-color: hsla(0, 0%, 1%, 0.69);">
JS:
jQuery(function($){
var overlay = $('#scid-overlay');
var visiblePanel;
$(".scid-hook-link").click(function(event){
openPanel(event);
});
$('.scid-close-button').click(function(event) {
closePanel(event);
});
overlay.click(function(event) {
closePanel(event);
});
function openPanel(event){
event.preventDefault();
var id = $(event.target).attr('id').replace('hook', 'popup');
$(event.target).closest('figure').addClass(' scid-popup');
document.querySelector('#' + id).className += (' scid-panel-open');
overlay.removeClass('overlay-close');
overlay.addClass('overlay-open');
sizePanel(id);
window.location.hash = "#" + id;
visiblePanel = document.querySelector('.scid-panel-open');
};
function closePanel(event){
if(event){
event.preventDefault();
}
if(visiblePanel) {
var id = visiblePanel.id;
console.log(id)
console.log(visiblePanel);
document.querySelector('.scid-popup').classList.remove('scid-popup');
visiblePanel.classList.remove('scid-panel-open');
overlay.removeClass('overlay-open');
overlay.addClass('overlay-close');
sizePanel(id);
}
}
function sizePanel(id) {
var panel = document.querySelector( '#' + id);
if (panel.offsetHeight == 0) {
panel.style.height = panel.scrollHeight + 'px';
} else {
panel.style.height = 0 +'px';
window.location.hash = "";
visiblePanel = null;
}
};
window.onhashchange = function() {
if(visiblePanel && window.location.hash != '#' + visiblePanel.id){
closePanel();
}
}
});
CSS:
.overlay-close {
height: 0;
opacity: 0;
}
.overlay-open {
height: 100%;
opacity: 1
overflow: scroll;
overflow-y: auto;
visibility: visible;
z-index: 69;
}
最佳答案
Body overflow 工作正常,但您还向创建滚动条的 HTML 标记提供了 overflow-x: scroll
。
你必须在你的 css 中删除 html 样式
html{
overflow-x: hidden;
}
然后 body 上的溢出将正常工作。
关于javascript - 弹出窗口打开时防止正文滚动,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46849492/