切换多个溢出y元素时的位置位移 [英] Position displacement when toggling several overflow-y Elements

查看:159
本文介绍了切换多个溢出y元素时的位置位移的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个问题,我不知道如何解决,希望有人在这里可以淡化一些光。

I have a problem which I don't know how to solve, hopefully someone here can shed some light into it.

我有一个非常简单的布局a href =http://jsbin.com/UFoRIYex/586 =nofollow> JSBin )具有水平居中的标题,某些内容可以体验垂直滚动,粘性页脚和画布外导航菜单。我想阻止用户在侧边栏打开时滚动页面,我通过在< html> 标签上切换一个类来实现:

I have a very simple layout (JSBin) with a horizontally centered header, some content to experience vertical scrolling, a sticky footer and an off-canvas navigation menu. I want to prevent the user from scrolling the page when the sidebar is opened, I'm doing that by toggling a class on the <html> tag:

$('button').click(function () {
    $('html').toggleClass('sidebar');
});

.sidebar 进入视图并禁用对内容的滚动:

The .sidebar class will transition the sidebar into view and disable scrolling on the content:

html {
  overflow-y: scroll; /* default state, always shows scrollbar */
}

html.sidebar {
  overflow-y: hidden; /* hides scrollbar when .sidebar is on canvas */
}

html.sidebar aside {
  -webkit-transform: translate3d(-100%, 0, 0); /* places .sidebar on canvas */
}

问题是,元素在< html> 滚动条的宽度。

The problem is, it displaces every element in the page by whatever width the <html> scrollbar had.

有任何方法来防止(最好不使用Javascript)?

Is there any way to prevent this shift in position (preferably without resorting to Javascript)?

这是 JSBin编辑器

更新 :似乎Javascript不是一个选项,滚动宽度计算是不可靠的。

Update: Seems that Javascript isn't an option, the scroll width calculation is not reliable at all.

推荐答案

code> ,以补偿宽度变化

You can toggle the margin-right of .container to compensate for the change in width

$(function () {      
  $('button').click(function () {
    var marginR = $(".container").css("margin-right") == sWidth+"px" ? "auto" : sWidth;
    $(".container").css("margin-right", marginR);
    $('html').toggleClass('sidebar');
  });

});

function getScrollbarWidth() {
    var outer = document.createElement("div");
    outer.style.visibility = "hidden";
    outer.style.width = "100px";
    outer.style.msOverflowStyle = "scrollbar"; // needed for WinJS apps

    document.body.appendChild(outer);

    var widthNoScroll = outer.offsetWidth;
    // force scrollbars
    outer.style.overflow = "scroll";

    // add innerdiv
    var inner = document.createElement("div");
    inner.style.width = "100%";
    outer.appendChild(inner);        

    var widthWithScroll = inner.offsetWidth;

    // remove divs
    outer.parentNode.removeChild(outer);

    return widthNoScroll - widthWithScroll;
}
var sWidth = getScrollbarWidth();

演示

滚动条宽度计算取自此回答

这篇关于切换多个溢出y元素时的位置位移的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆