前端tab切换瀑布流代码
时间: 2023-08-30 16:05:15 浏览: 124
以下是一个基于jQuery和Masonry库实现的前端tab切换瀑布流代码示例:
HTML代码:
```
<div class="tab-wrapper">
<ul class="tab-nav">
<li class="active"><a href="#tab1">Tab 1</a></li>
<li><a href="#tab2">Tab 2</a></li>
<li><a href="#tab3">Tab 3</a></li>
</ul>
<div class="tab-content">
<div id="tab1" class="tab-pane active">
<div class="grid">
<div class="grid-item"><img src="image1.jpg"></div>
<div class="grid-item"><img src="image2.jpg"></div>
<div class="grid-item"><img src="image3.jpg"></div>
<div class="grid-item"><img src="image4.jpg"></div>
<div class="grid-item"><img src="image5.jpg"></div>
</div>
</div>
<div id="tab2" class="tab-pane">
<div class="grid">
<div class="grid-item"><img src="image6.jpg"></div>
<div class="grid-item"><img src="image7.jpg"></div>
<div class="grid-item"><img src="image8.jpg"></div>
<div class="grid-item"><img src="image9.jpg"></div>
<div class="grid-item"><img src="image10.jpg"></div>
</div>
</div>
<div id="tab3" class="tab-pane">
<div class="grid">
<div class="grid-item"><img src="image11.jpg"></div>
<div class="grid-item"><img src="image12.jpg"></div>
<div class="grid-item"><img src="image13.jpg"></div>
<div class="grid-item"><img src="image14.jpg"></div>
<div class="grid-item"><img src="image15.jpg"></div>
</div>
</div>
</div>
</div>
```
CSS代码:
```
.tab-wrapper {
width: 100%;
margin: 0 auto;
}
.tab-nav {
list-style: none;
margin: 0;
padding: 0;
display: flex;
justify-content: center;
align-items: center;
border-bottom: 1px solid #ccc;
}
.tab-nav li {
margin: 0 10px;
}
.tab-nav li a {
display: block;
padding: 10px;
color: #333;
text-decoration: none;
}
.tab-nav li.active a {
color: #f00;
border-bottom: 2px solid #f00;
}
.tab-content {
padding: 20px;
}
.grid {
margin: 0;
padding: 0;
}
.grid-item {
margin: 10px;
float: left;
}
.grid-item img {
max-width: 100%;
}
```
JavaScript代码:
```
$(document).ready(function() {
// 初始化瀑布流布局
var $grid = $('.grid').masonry({
itemSelector: '.grid-item',
columnWidth: '.grid-sizer',
percentPosition: true
});
// 切换tab时重新布局
$('.tab-nav a').on('click', function(e) {
e.preventDefault();
var $tab = $(this).attr('href');
$('.tab-nav li').removeClass('active');
$(this).parent().addClass('active');
$('.tab-pane').removeClass('active');
$($tab).addClass('active');
$grid.masonry('layout');
});
});
```
通过以上代码,我们实现了一个基于jQuery和Masonry库的前端tab切换瀑布流效果。当用户点击不同的tab标签时,页面中的瀑布流布局会重新布局,以适应当前tab内容的大小和数量。
阅读全文