gpt4 book ai didi

javascript - 当父项太小时防止 div 换行

转载 作者:行者123 更新时间:2023-11-27 23:03:47 25 4
gpt4 key购买 nike

我怎样才能阻止这个父 div 内的 div 换行而不是被切断?

代码:

var slider = document.getElementById("slider"),
cont1 = document.getElementById("container1"),
cont2 = document.getElementById("container2");

slider.addEventListener("input", function() {
cont1.style.width = slider.value + "px";
cont2.style.width = slider.value + "px";
}, false);
#item {
width: 100px;
height: 100px;
float: left;
}

.container {
height: 100px;
background-color: #ccc;
}
<p>use slider to change width of the container</p>
<input id="slider" type="range" max="500">
<p>overflow: hidden</p>
<div class="container" id="container1" style="width: 300px; overflow: hidden;">
<div id="item" style="background-color: red;"></div>
<div id="item" style="background-color: green;"></div>
</div>

<p>overflow: visible</p>
<div class="container" id="container2" style="width: 300px; overflow: visible;">
<div id="item" style="background-color: red;"></div>
<div id="item" style="background-color: green;"></div>
</div>

jsfiddle

如您所见,当我更改父 div 的大小时,div 会自动换行。经过搜索,我找到了两个解决方案。其中之一需要通过使用绝对定位的 div 为容器设置宽度。另一个使用了 white-space: none,但没有成功。

最佳答案

考虑 inline-block 而不是 float ,您将能够使用 with-space 技巧:

var slider = document.getElementById("slider"),
cont1 = document.getElementById("container1"),
cont2 = document.getElementById("container2");

slider.addEventListener("input", function() {
cont1.style.width = slider.value + "px";
cont2.style.width = slider.value + "px";
}, false);
#item {
width: 100px;
height: 100px;
display: inline-block;
}

.container {
height: 100px;
background-color: #ccc;
white-space: nowrap;
font-size: 0; /*to avoid white-space between inline-block*/
}
<p>use slider to change width of the container</p>
<input id="slider" type="range" max="500">
<p>overflow: hidden</p>
<div class="container" id="container1" style="width: 300px; overflow: hidden;">
<div id="item" style="background-color: red;"></div>
<div id="item" style="background-color: green;"></div>
</div>

<p>overflow: visible</p>
<div class="container" id="container2" style="width: 300px; overflow: visible;">
<div id="item" style="background-color: red;"></div>
<div id="item" style="background-color: green;"></div>
</div>

关于javascript - 当父项太小时防止 div 换行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51032630/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com