javascript - 使用 JS 在主列上响应宽度

标签 javascript jquery html css

我有一个包含 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>

最佳答案

这可以使用 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>

关于javascript - 使用 JS 在主列上响应宽度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27751988/

相关文章:

javascript - 在 Jquery 中验证表单的输入字段

jquery - 在 Silverstripe 3 中加载带有滑动动画的新页面(使用 Ajax?)

html - 为什么以像素指定的 div 宽度变得越来越小?

javascript - 保存链接分配值以及转到其他页面

javascript - 基于窗口大小的工具提示定位

javascript - 对我的 HTML 输入文本求和不起作用

javascript - 从表中删除行导致 TypeError

c# - 为什么我不能删除这个 cookie?

jquery - 在asp.net mvc 4.0网站中实现聊天?

javascript - 在表单输入上按回车键使其失去焦点