我在列弹性框中有一些元素,它本身就是一个弹性元素。
当我按下按钮时,最后一个元素的内容会改变它的宽度,并成为弹性盒中更宽的元素,使其更宽。 我想阻止这种情况,因为它不漂亮。当我按下按钮时,宽度不得改变。
请参阅代码片段以进行说明。
var thirdDivs = [...document.querySelectorAll('.child.third')];
document.getElementById('toggleButton').addEventListener('click', function() {
thirdDivs.map((thirdDiv) => {thirdDiv.classList.toggle('hidden');});
});
main{
display: flex;
}
.container {
display: flex;
flex-flow: column wrap;
border: 1px solid red
}
.hidden {
display: none;
}
<p> I don't want that red box to change size when I press the button. I want the text to be on two different lines</p>
<button id="toggleButton">Switch</button>
<main>
<div class='container'>
<div class='child first'>
<p>Some content</p>
</div>
<div class='child second'>
<p>Some more content</p>
</div>
<div class='child third'>
<p>A short text</p>
</div>
<div class='child third hidden'>
<p>A very much more longer text<p>
</div>
</div>
</main>
我尝试使用 flex-grow 和 flex-shrink 但没有成功。
不幸的是,你应该使用 CSS 或 JS 设置容器的宽度:
var thirdDivs = [...document.querySelectorAll('.child.third')];
document.getElementById('toggleButton').addEventListener('click', function() {
thirdDivs.map((thirdDiv) => {thirdDiv.classList.toggle('hidden');});
});
const $cont = document.querySelector('.container');
$cont.style.width = $cont.offsetWidth + 'px'
main{
display: flex;
}
.container {
display: flex;
flex-flow: column wrap;
border: 1px solid red
}
.hidden {
display: none;
}
<p> I don't want that red box to change size when I press the button. I want the text to be on two different lines</p>
<main>
<div class='container'>
<div class='child first'>
<p>Some content</p>
</div>
<div class='child second'>
<p>Some more content</p>
</div>
<div class='child third'>
<p>A short text</p>
</div>
<div class='child third hidden'>
<p>A very much more longer text<p>
</div>
</div>
</main>
<button id="toggleButton">Switch</button>