确定 flexbox 的所需宽度
Determine the desired width of a flexbox
我的页面底部有一个按钮面板。该容器是一个 flexbox,所有按钮排成一行,没有换行。这些按钮是 <button>
或 <a>
元素,其内容为图标和文本。现在由于页面太窄无法包含所有按钮,我想将按钮缩小到可用 space。只有最右边的按钮会收缩。当其宽度低于某个阈值时,按钮将仅折叠为图标。然后右边的下一个按钮缩小了。
我可以用 JavaScript 实现所有这些,但我需要知道按钮的内容是否适合页面。无论我尝试什么,flexbox 都不会超出其父级 div,但按钮仍然绘制到它的右端,因此 flexbox 永远不会比其容器宽。
这种方法对表格很有效。表总是和它们的内容一样宽,即使它们的父表没有那么宽。但是 flexbox 似乎永远不会这样做。
如何使用 JavaScript 或 jQuery 代码找出 flexbox 所需的宽度?那是适合所有 flexbox 内容所需的宽度。
名称"desired width"来自WindowsForms或WPF,但似乎没有在HTML中使用。因此,如果我需要更好的搜索条件,请告诉我。
举个例子。 .container
的宽度限制为200px;在我的例子中,它仅限于页面宽度减去填充。
* {
box-sizing: border-box;
}
.container {
width: 200px;
background: azure;
padding: 10px;
}
.buttons {
background: bisque;
padding: 10px;
display: flex;
white-space: nowrap;
}
.buttons button,
.buttons a {
flex-shrink: 0;
}
<div class="container">
<div class="buttons">
<button>Button 1</button>
<button>Button 2</button>
<button>Button 3</button>
<button>Button 4</button>
</div>
</div>
经过大量尝试并偶然发现 ,这段代码似乎可以满足我的需要:
// Returns the total width of all children including their margins.
function childrenWidth(parent) {
let contentWidth = 0;
parent.children().each(function () {
contentWidth += $(this).outerWidth(true);
});
return contentWidth;
}
let contentWidth = childrenWidth(flexBox);
这需要 jQuery。
但这也可能足以做到这一点,它 returns 一个四舍五入的值:
// flexBox is a jQuery object
let contentWidth = flexBox[0].scrollWidth;
没有 jQuery 也可以。
我使用当前版本的 Firefox、Chrome 和 Edge 对此进行了测试。它在 IE11 中做了一些事情,尽管不完全相同。我不确定它是否与此代码有关。我的 IE11 支持没有扩展到响应式布局,所以我现在可以接受。
我的页面底部有一个按钮面板。该容器是一个 flexbox,所有按钮排成一行,没有换行。这些按钮是 <button>
或 <a>
元素,其内容为图标和文本。现在由于页面太窄无法包含所有按钮,我想将按钮缩小到可用 space。只有最右边的按钮会收缩。当其宽度低于某个阈值时,按钮将仅折叠为图标。然后右边的下一个按钮缩小了。
我可以用 JavaScript 实现所有这些,但我需要知道按钮的内容是否适合页面。无论我尝试什么,flexbox 都不会超出其父级 div,但按钮仍然绘制到它的右端,因此 flexbox 永远不会比其容器宽。
这种方法对表格很有效。表总是和它们的内容一样宽,即使它们的父表没有那么宽。但是 flexbox 似乎永远不会这样做。
如何使用 JavaScript 或 jQuery 代码找出 flexbox 所需的宽度?那是适合所有 flexbox 内容所需的宽度。
名称"desired width"来自WindowsForms或WPF,但似乎没有在HTML中使用。因此,如果我需要更好的搜索条件,请告诉我。
举个例子。 .container
的宽度限制为200px;在我的例子中,它仅限于页面宽度减去填充。
* {
box-sizing: border-box;
}
.container {
width: 200px;
background: azure;
padding: 10px;
}
.buttons {
background: bisque;
padding: 10px;
display: flex;
white-space: nowrap;
}
.buttons button,
.buttons a {
flex-shrink: 0;
}
<div class="container">
<div class="buttons">
<button>Button 1</button>
<button>Button 2</button>
<button>Button 3</button>
<button>Button 4</button>
</div>
</div>
经过大量尝试并偶然发现
// Returns the total width of all children including their margins.
function childrenWidth(parent) {
let contentWidth = 0;
parent.children().each(function () {
contentWidth += $(this).outerWidth(true);
});
return contentWidth;
}
let contentWidth = childrenWidth(flexBox);
这需要 jQuery。
但这也可能足以做到这一点,它 returns 一个四舍五入的值:
// flexBox is a jQuery object
let contentWidth = flexBox[0].scrollWidth;
没有 jQuery 也可以。
我使用当前版本的 Firefox、Chrome 和 Edge 对此进行了测试。它在 IE11 中做了一些事情,尽管不完全相同。我不确定它是否与此代码有关。我的 IE11 支持没有扩展到响应式布局,所以我现在可以接受。