我试图禁用父母的html/身体滚动条,而我正在使用一个灯箱。这里的主要词是disable。我不想用溢出来隐藏它。

这样做的原因是overflow: hidden会使站点跳转并占用原来滚动的区域。

我想知道是否有可能禁用滚动条,同时仍然显示它。


当前回答

你可以用overflow: hidden隐藏正文的滚动条,同时设置一个边距,这样内容就不会跳转:

let marginRightPx = 0;
if(window.getComputedStyle) {
    let bodyStyle = window.getComputedStyle(document.body);
    if(bodyStyle) {
        marginRightPx = parseInt(bodyStyle.marginRight, 10);
    }
}

let scrollbarWidthPx = window.innerWidth - document.body.clientWidth;
Object.assign(document.body.style, {
    overflow: 'hidden',
    marginRight: `${marginRightPx + scrollbarWidthPx}px`
});

然后你可以在页面上添加一个禁用的滚动条来填补空白:

textarea { overflow-y:滚动; overflow-x:隐藏; 宽度:11 px; 大纲:没有; 调整:没有; 位置:固定; 上图:0; 右:0; 底部:0; 边界:0; } textarea > < textarea > < /

我在我自己的灯箱实现中就是这样做的。目前看来还不错。

其他回答

另一个在固定模式上摆脱内容跳转的解决方案是,当删除主体滚动时,将页面宽度归一化:

body {width: 100vw; overflow-x: hidden;}

然后你可以玩固定位置或溢出:隐藏的身体时,模式是开放的。但它会隐藏水平滚动条-通常他们不需要响应式网站。

我用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);
    }
}

你可以保持overflow:隐藏,但手动管理滚动位置:

在显示实际滚动位置之前保持跟踪:

var scroll = [$(document).scrollTop(),$(document).scrollLeft()];
//show your lightbox and then reapply scroll position
$(document).scrollTop(scroll[0]).scrollLeft(scroll[1]);

应该可以

包含jQuery:


禁用

$.fn.disableScroll = function() {
    window.oldScrollPos = $(window).scrollTop();

    $(window).on('scroll.scrolldisabler',function ( event ) {
       $(window).scrollTop( window.oldScrollPos );
       event.preventDefault();
    });
};

启用

$.fn.enableScroll = function() {
    $(window).off('scroll.scrolldisabler');
};

使用

//disable
$("#selector").disableScroll();
//enable
$("#selector").enableScroll();

所有基于javascript的modal/lightbox系统在html标签或body标签上显示modal/lightbox时都会使用溢出。

当lightbox显示时,js会推送一个隐藏在html或body标签上的溢出。 当lightbox被隐藏时,有些人会删除隐藏的,有些人会在html或body标签上推一个溢出自动。

在Mac上工作的开发人员没有看到滚动条的问题。

只需替换隐藏的unset不看到内容滑动下的模式删除滚动条。

Lightbox开放/显示:

<html style="overflow: unset;"></html>

Lightbox隐藏/关闭:

<html style="overflow: auto;"></html>