我有 4 个 div
类 button
。
有时一个页面可能有 5 个具有该类名称的 div
,因此我需要更改它们的宽度以使它们适合页面。
这是我的CSS:
<style>
.button{
width:25%;
}
@media only screen and (max-device-width: 480px) {
.button{
width:100%;
}
}
</style>
这是我的 html:
<div id="center">
<div class="button" style=" background: blue; float:left;">test</div>
<div class="button" style=" background: red; float:left;">test</div>
<div class="button" style=" background: purple; float:left;">test</div>
<div class="button" style=" background:orange; float:left;">test</div>
</div>
这是我在 javascript 中的尝试
<script type="text/javascript">
$(document).ready(function() {
if($("#center div").length == 4);
button.style.width = '25%';
}
else{
button.style.width = '20%';
}
});
</script>
但是这个脚本不起作用。
最佳答案
作为 JavaScript 解决方案,您可以获得 .button
子级的数量并将它们的宽度设置为 100%/number-of-chilren
。
var divs = $('#center').children('.button');
divs.width(100 / divs.length + '%');
.button { float:left; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="center">
<div class="button" style="background: blue;">test</div>
<div class="button" style="background: red;">test</div>
<div class="button" style="background: purple;">test</div>
<div class="button" style="background:orange;">test</div>
</div>
但是,如果灵活的盒子布局是一个选项,您可以通过将 display: flex
添加到容器并为子级添加 flex: 1
来实现相同的结果。
#center {
display: flex;
}
.button {
flex: 1
}
<div id="center">
<div class="button" style=" background: blue;">test</div>
<div class="button" style=" background: red;">test</div>
<div class="button" style=" background: purple;">test</div>
<div class="button" style=" background:orange;">test</div>
</div>
为简洁起见省略了 vendor 前缀。
关于javascript - 根据子 div 的总数更改宽度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29363008/