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

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

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


当前回答

我也遇到过类似的问题:左侧菜单出现时,无法滚动。一旦高度设置为100vh,滚动条就会消失,内容会向右抽搐。

因此,如果你不介意保持滚动条启用(但设置窗口全高,这样它实际上不会滚动到任何地方),那么另一种可能性是设置一个小的底部边距,这将保持滚动条显示:

body {
    height: 100vh;
    overflow: hidden;
    margin: 0 0 1px;
}

其他回答

包含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();

我注意到YouTube网站就是这么做的。所以通过检查它一点,我已经能够确定他们正在使用@聚合物/铁覆盖-行为,幸运的是,它可以在web组件/聚合物之外使用:

import {
    pushScrollLock,
    removeScrollLock,
} from '@polymer/iron-overlay-behavior/iron-scroll-manager';

// lock scroll everywhere except scrollElement
pushScrollLock(scrollElement);

// restore scrolling
removeScrollLock(scrollElement);

允许滚动选定的元素 不会以任何方式干扰样式 是否在YouTube网站上进行了实战测试

这似乎是一个成熟的解决方案,当然也是我能找到的最好的解决方案。包装有点重,但我猜大部分都是分开的,当只进口铁卷轴管理器。

干杯

在公认的解决方案基础上增加了四个小补充:

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]);

应该可以

你不能禁用滚动事件,但是你可以禁用导致滚动的相关操作,比如鼠标滚轮和touchmove:

$('body').on('mousewheel touchmove', function(e) {
      e.preventDefault();
});