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


当前回答

@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);
  }
});

其他回答

我试图修复可能由twitter bootstrap .modal-open类应用于body引起的相同问题。解决方案html {overflow-y: scroll}不起作用。我发现的一个可能的解决方案是添加{width: 100%;宽度:100vw}到HTML元素。

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

body {
  scrollbar-gutter: stable both-edges;
}

新的css规范,将有助于滚动条重新定位的方式: https://developer.mozilla.org/en-US/docs/Web/CSS/scrollbar-gutter

我的方法是使轨道透明。滚动条拇指颜色为#C1C1C1,以匹配默认的滚动条拇指颜色。你可以做任何你喜欢的东西:)

试试这个:

html {
    overflow-y: scroll;
}

body::-webkit-scrollbar {
    width: 0.7em;
    background-color: transparent;
}

body::-webkit-scrollbar-thumb {
    background: #C1C1C1;
    height:30px;
}

body::-webkit-scrollbar-track-piece
{
    display:none;
}

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