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


当前回答

我的方法是使轨道透明。滚动条拇指颜色为#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;
}

其他回答

我已经在我的一个网站上解决了这个问题,通过显式地在javascript中设置主体的宽度为视口大小减去滚动条的宽度。我使用这里记录的基于jQuery的函数来确定滚动条的宽度。

<body id="bodyid>

var bodyid = document.getElementById('bodyid');
bodyid.style.width = window.innerWidth - scrollbarWidth() + "px";

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

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

我曾经有过这样的问题,但是解决它的简单方法是这样的(这对我来说很有效):

CSS文件类型:

body{overflow-y:scroll;}

就这么简单!:)

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