图像拼接墙(Image Mosaic Wall)是一种将多张图片以特定布局方式排列展示的网页效果,常见于图片画廊、作品集展示等场景。jQuery作为流行的JavaScript库,可以简化DOM操作和动画效果实现,非常适合用于创建动态的图像拼接墙。
<div class="mosaic-wall">
<div class="mosaic-item">
<img src="image1.jpg" alt="Image 1">
</div>
<div class="mosaic-item">
<img src="image2.jpg" alt="Image 2">
</div>
<!-- 更多图片... -->
</div>
.mosaic-wall {
width: 100%;
overflow: hidden;
position: relative;
}
.mosaic-item {
position: absolute;
transition: all 0.3s ease;
}
.mosaic-item img {
width: 100%;
height: auto;
display: block;
}
$(document).ready(function() {
var $container = $('.mosaic-wall');
var $items = $('.mosaic-item');
var columnCount = 4;
var spacing = 10;
function layoutMosaic() {
var containerWidth = $container.width();
var itemWidth = (containerWidth - (columnCount - 1) * spacing) / columnCount;
var columnsHeight = new Array(columnCount).fill(0);
$items.each(function(index) {
var $item = $(this);
var itemHeight = $item.height() * (itemWidth / $item.width());
$item.css({
width: itemWidth,
height: itemHeight
});
// 找到当前最短的列
var minCol = 0;
var minHeight = columnsHeight[0];
for (var i = 1; i < columnCount; i++) {
if (columnsHeight[i] < minHeight) {
minHeight = columnsHeight[i];
minCol = i;
}
}
// 定位元素
$item.css({
left: minCol * (itemWidth + spacing),
top: minHeight + (minHeight > 0 ? spacing : 0)
});
// 更新列高
columnsHeight[minCol] = minHeight + itemHeight + (minHeight > 0 ? spacing : 0);
});
// 设置容器高度
$container.height(Math.max(...columnsHeight));
}
// 初始布局和窗口调整时重新布局
layoutMosaic();
$(window).resize(layoutMosaic);
});
$(function() {
var $wall = $('.mosaic-wall');
var $items = $('.mosaic-item');
var colCount = 0;
var colWidth = 0;
var spacing = 15;
function arrangeItems() {
var wallWidth = $wall.width();
colWidth = $items.outerWidth(true);
colCount = Math.floor(wallWidth / colWidth);
colWidth = Math.floor(wallWidth / colCount);
var colHeights = new Array(colCount).fill(0);
$items.each(function() {
var $item = $(this);
var minCol = 0;
var minHeight = colHeights[0];
for (var i = 1; i < colCount; i++) {
if (colHeights[i] < minHeight) {
minHeight = colHeights[i];
minCol = i;
}
}
$item.css({
'position': 'absolute',
'left': minCol * colWidth + 'px',
'top': minHeight + 'px',
'width': colWidth - spacing + 'px'
});
colHeights[minCol] += $item.outerHeight(true);
});
$wall.height(Math.max.apply(null, colHeights));
}
// 图片加载完成后布局
var loaded = 0;
$items.find('img').each(function() {
$(this).on('load', function() {
loaded++;
if (loaded === $items.length) {
arrangeItems();
}
}).each(function() {
if (this.complete) $(this).trigger('load');
});
});
$(window).resize(function() {
arrangeItems();
});
});
原因:图片未完全加载时获取的高度不准确
解决方案:
原因:大量DOM操作导致页面卡顿
解决方案:
原因:图片高度计算不精确
解决方案:
原因:窗口大小变化时布局未及时调整
解决方案:
通过以上方法和代码示例,您可以实现一个功能完善、性能良好的基于jQuery的图像拼接墙布局。
没有搜到相关的文章