我有一个网站与中心对齐的DIV。现在,一些页面需要滚动,一些不需要。当我从一种类型移动到另一种类型时,滚动条的出现将页面移向一侧几个像素。有没有什么方法可以避免这种情况,而不显式地在每个页面上显示滚动条?


当前回答

我使用一些jquery来解决这个问题

$('html').css({
    'overflow-y': 'hidden'
});

$(document).ready(function(){
  $(window).load(function() {
    $('html').css({
      'overflow-y': ''
    });
  });
});

其他回答

@kashesandr的解决方案对我有用,但为了隐藏水平滚动条,我为身体添加了一个样式。这里是完整的解决方案:

CSS

<style>
/* prevent layout shifting and hide horizontal scroll */
html {
  width: 100vw;
}
body {
  overflow-x: hidden;
}
</style>

JS

$(function(){
    /**
     * For multiple modals.
     * Enables scrolling of 1st modal when 2nd modal is closed.
     */
    $('.modal').on('hidden.bs.modal', function (event) {
      if ($('.modal:visible').length) {
        $('body').addClass('modal-open');
      }
    });
});

JS唯一的解决方案(当第二模式从第一模式打开):

/**
 * For multiple modals.
 * Enables scrolling of 1st modal when 2nd modal is closed.
 */
$('.modal').on('hidden.bs.modal', function (event) {
  if ($('.modal:visible').length) {
    $('body').addClass('modal-open');
    $('body').css('padding-right', 17);
  }
});

我不这么认为。但样式体与溢出:滚动应该做。不过你好像知道。

与公认的答案相反,即使内容没有溢出屏幕,也建议在浏览器窗口上使用永久滚动条,我更喜欢使用:

html{
  height:101%;
}

这是因为如果内容溢出,滚动条的外观更有意义。

这个比这个更有意义。

html {
  overflow-x: hidden;
  margin-right: calc(-1 * (100vw - 100%));
}

的例子。点击“改变最小高度”按钮。

使用calc(100vw - 100%)我们可以计算滚动条的宽度(如果它不显示,它将是0)。想法:使用负margin-right,我们可以将<html>的宽度增加到这个宽度。你会看到一个水平滚动条-它应该隐藏使用overflow-x: hidden。

我不知道这是否是一个旧帖子,但我有同样的问题,如果你想垂直滚动,你应该尝试溢出-y:滚动