我的这个页面包含 4 列,每列宽度为 25%,高度为 100%,还有 4 个用于切换每个列的按钮。问题是我想不出一种方法来相应地调整它们的大小。
当 4 列可见时,每列的宽度应为 25% 当 3 列可见时,每列的宽度应为 33% 等等 ... 但是,当我将隐藏的再次切换为可见时,它们需要相应地进行调整,有什么建议吗?
我为我的问题创建了一个片段。
$("#button-column-1").click(function() {
$("#column-1").toggle(1500);
});
$("#button-column-2").click(function() {
$("#column-2").toggle(1500);
});
$("#button-column-3").click(function() {
$("#column-3").toggle(1500);
});
$("#button-column-4").click(function() {
$("#column-4").toggle(1500);
});
.column {
float: left;
height: 100vh;
width: 25%;
-webkit-box-shadow:inset 0px 0px 0px 1px black;
-moz-box-shadow:inset 0px 0px 0px 1px black;
box-shadow:inset 0px 0px 0px 1px black;
}
<html>
<head> </head>
<body>
<div id="button-container">
<button type="button" id="button-column-1">Column 1</button>
<button type="button" id="button-column-2">Column 2</button>
<button type="button" id="button-column-3">Column 3</button>
<button type="button" id="button-column-4">Column 4</button>
</div>
<div class="column" id="column-1">
1
</div>
<div class="column" id="column-2">
2
</div>
<div class="column" id="column-3">
3
</div>
<div class="column" id="column-4">
4
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
</body>
</html>
最佳答案
使用flexbox与您的布局完美搭配。将您的列包装在 block 元素中,我使用了一个部分,然后添加以下 CSS:
/* This is the element that contains the columns */
#setB {
display:flex;
flex-wrap:nowrap;
justify-content: center;
}
/* This ruleset will make the columns stretch and shrink when there's empty or less space. They will start adjusting when they are 24% or more in width.
.column {
flex: 1 1 24%;
...
片段
$("#btn1").click(function() {
$("#col1").toggle(1500);
});
$("#btn2").click(function() {
$("#col2").toggle(1500);
});
$("#btn3").click(function() {
$("#col3").toggle(1500);
});
$("#btn4").click(function() {
$("#col4").toggle(1500);
});
#setB {
display: flex;
flex-wrap: nowrap;
justify-content: center;
}
.column {
flex: 1 1 24%;
height: 100vh;
width: 25%;
-webkit-box-shadow: inset 0px 0px 0px 1px black;
-moz-box-shadow: inset 0px 0px 0px 1px black;
box-shadow: inset 0px 0px 0px 1px black;
}
<html>
<head></head>
<body>
<fieldset id="setA">
<button id="btn1">Column 1</button>
<button id="btn2">Column 2</button>
<button id="btn3">Column 3</button>
<button id="btn4">Column 4</button>
</fieldset>
<section id='setB'>
<div class="column" id="col1">
1
</div>
<div class="column" id="col2">
2
</div>
<div class="column" id="col3">
3
</div>
<div class="column" id="col4">
4
</div>
</section>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
</body>
</html>
关于javascript - 切换 4 个 div 并在屏幕的整个宽度中显示它们,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41120149/