【问题标题】:Responsive width on main column using JS使用JS在主列上的响应宽度
【发布时间】:2015-03-01 08:45:47
【问题描述】:

我有一个带有 2 个列(主栏和侧边栏)的响应式布局。侧栏的宽度是固定的,主栏的宽度是响应式的。将侧边栏设置为固定宽度,如果侧边栏明显下降,我无法将主列设置为 100%。有没有办法让javascript根据浏览器大小计算主列的宽度? (考虑到应该在它旁边的固定宽度列)

#main {
	background-color: #0F0;
	float: left;
	height: 400px;
	width: 100%;
}
#sidebar {
	background-color: #C60;
	float: right;
	height: 400px;
	width: 300px;
}
<div id="main">
</div>

<div id="sidebar">
</div>

【问题讨论】:

    标签: javascript jquery html css


    【解决方案1】:

    这可以使用 CSS 的 calc() 函数来实现。

    #main {
      background-color: #0F0;
      float: left;
      height: 400px;
      width: calc(100% - 300px);
    }
    #sidebar {
      background-color: #C60;
      float: right;
      height: 400px;
      width: 300px;
    }
    body {
      margin: 0;
    }
    <div id="main">
    </div>
    <div id="sidebar">
    </div>

    如果你真的想使用 JavaScript,你需要将 mainwidth 设置为等于 windowwidth 没有滚动条 (document.body.clientWidth) 减去 sidebarwidth

    另外,doMath() 函数需要在 window 调整大小时执行。

    var main = document.getElementById('main');
    var sidebar = document.getElementById('sidebar');
    
    function doMath() {
      main.style.width = document.body.clientWidth - sidebar.offsetWidth + 'px';
    }
    
    doMath();
    window.onresize = doMath;
    #main {
      background-color: #0F0;
      float: left;
      height: 400px;
      width: 100%;
    }
    #sidebar {
      background-color: #C60;
      float: right;
      height: 400px;
      width: 300px;
    }
    body {
      margin: 0;
    }
    <div id="main">
    </div>
    <div id="sidebar">
    </div>

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2014-10-10
      • 2016-01-15
      • 2019-07-13
      • 2020-11-26
      • 1970-01-01
      • 1970-01-01
      • 2014-04-09
      相关资源
      最近更新 更多