我试图禁用父母的html/身体滚动条,而我正在使用一个灯箱。这里的主要词是disable。我不想用溢出来隐藏它。
这样做的原因是overflow: hidden会使站点跳转并占用原来滚动的区域。
我想知道是否有可能禁用滚动条,同时仍然显示它。
我试图禁用父母的html/身体滚动条,而我正在使用一个灯箱。这里的主要词是disable。我不想用溢出来隐藏它。
这样做的原因是overflow: hidden会使站点跳转并占用原来滚动的区域。
我想知道是否有可能禁用滚动条,同时仍然显示它。
当前回答
在公认的解决方案基础上增加了四个小补充:
Apply 'noscroll' to html instead of to body to prevent double scroll bars in IE To check if there's actually a scroll bar before adding the 'noscroll' class. Otherwise, the site will also jump pushed by the new non-scrolling scroll bar. To keep any possible scrollTop so the entire page doesn't go back to the top (like Fabrizio's update, but you need to grab the value before adding the 'noscroll' class) Not all browsers handle scrollTop the same way as documented at http://help.dottoro.com/ljnvjiow.php
完整的解决方案,似乎适用于大多数浏览器:
CSS
html.noscroll {
position: fixed;
overflow-y: scroll;
width: 100%;
}
禁用滚动
if ($(document).height() > $(window).height()) {
var scrollTop = ($('html').scrollTop()) ? $('html').scrollTop() : $('body').scrollTop(); // Works for Chrome, Firefox, IE...
$('html').addClass('noscroll').css('top',-scrollTop);
}
启用滚动
var scrollTop = parseInt($('html').css('top'));
$('html').removeClass('noscroll');
$('html,body').scrollTop(-scrollTop);
感谢法布里齐奥和德扬把我带到了正确的轨道上,感谢布罗丁戈解决了双滚动条的问题
其他回答
你可以保持overflow:隐藏,但手动管理滚动位置:
在显示实际滚动位置之前保持跟踪:
var scroll = [$(document).scrollTop(),$(document).scrollLeft()];
//show your lightbox and then reapply scroll position
$(document).scrollTop(scroll[0]).scrollLeft(scroll[1]);
应该可以
我是OP
在fcalderan回答的帮助下,我能够形成一个解决方案。我把我的解决方案留在这里,因为它带来了如何使用它的清晰度,并增加了一个非常重要的细节,宽度:100%;
我添加了这个类
body.noscroll
{
position: fixed;
overflow-y: scroll;
width: 100%;
}
这对我很有用,我用的是fantyapp。
我用scrollLock方法解决了这个问题,该方法为滚动轮事件和按下键事件设置侦听器,并使用preventScroll方法处理这些事件。就像这样:
preventScroll = function (e) {
// prevent scrollwheel events
e.preventDefault();
e.stopPropagation();
// prevent keydown events
var keys = [32, 33, 34, 35, 37, 38, 39, 40];
if (keys.includes(e.keyCode)) {
e.preventDefault();
}
return false;
}
scrollLock = function (lock) {
if (lock) {
document.querySelector("#container").addEventListener("wheel", preventScroll);
document.addEventListener("keydown", preventScroll);
}
else {
document.querySelector("#container").removeEventListener("wheel", preventScroll);
document.querySelector("#container").removeEventListener("keydown", preventScroll);
}
}
粗糙但有效的方法是强制滚动回顶部,从而有效地禁用滚动:
var _stopScroll = false;
window.onload = function(event) {
document.onscroll = function(ev) {
if (_stopScroll) {
document.body.scrollTop = "0px";
}
}
};
打开灯箱时升起旗子,关闭灯箱时降下旗子。
现场测试用例。
我有一些其他固定的元素在页面和设置主体的位置固定导致了一堆其他问题,所以我做了一个hack的方式:
const scrollbarWidth = window.innerWidth - document.documentElement.clientWidth;
// on opening modal
document.body.style.overflow = "hidden"
document.body.style.paddingRight = `${scrollbarWidth}px`
// on closing modal
document.body.style.overflow = "unset",
document.body.style.paddingRight = "0px"
这个想法是添加一个与浏览器滚动条宽度相同的右填充,以模仿假滚动条并防止内容移动。