
如何在父元素内实现子元素的两行?
问题:
我想在红色框形父元素内排列子元素,使它们形成两行。当超出父元素范围时,初始状态下隐藏多余内容,并显示省略号按钮。点击该按钮时,隐藏内容将展开,并出现水平滚动条。
在线演示
HTML:
<div id="container" class="hidden">
<div id="flex-container">
<div class="item">item1</div>
<div class="item">item2</div>
<div class="item">item3</div>
<div class="item">item4</div>
<div class="item">item5</div>
<div class="item">item6</div>
<div class="item">item7</div>
<div class="item">item8</div>
<div class="item">item9</div>
<div class="item">item10</div>
<div id="more">...</div>
</div>
</div>
登录后复制
CSS:
#container {
width: 400px;
height: 200px;
border: 1px solid red;
position: relative;
}
#container.hidden {
overflow-x: hidden;
overflow-y: hidden;
}
#container.scroll {
overflow-x: scroll;
overflow-y: hidden;
}
#flex-container {
width: 800px;
height: 200px;
background: pink;
display: flex;
flex-wrap: wrap;
justify-content: space-around;
}
#flex-container .item {
width: 150px;
text-align: center;
background: yellow;
height: 94px;
display: flex-item;
}
#more {
display: block;
position: absolute;
top: 160px;
right: 10px;
z-index: 5;
width: 80px;
height: 30px;
background: green;
border-radius: 5px;
text-align: center;
color: white;
cursor: pointer;
}
登录后复制
JavaScript:
document.getElementById("more").onclick = function() {
this.style.display = "none";
document.getElementById("container").className = "scroll";
}
登录后复制
基本原理:
- 在容器 Div 中放置一个包含子元素的 flex 容器。容器 Div 设置为隐藏超出部分。
- 添加一个“更多”按钮,当点击时,将容器 Div 设为可滚动,允许查看隐藏的内容。
- 使用 JavaScript 确定何时显示“更多”按钮,例如当 flex 容器宽于容器 Div 时。
以上就是如何实现父元素内子元素两行,超出部分隐藏并显示省略号按钮?的详细内容,更多请关注米云其它相关文章!
