css布局之瀑布流布局

2021年1月3日,今天又是充满希望的一天。

html

<body>
	<div id="main">
		<div class="box">
			<!-- 模拟图片 -->
			<div style="height: 400px; background-color: aqua;">1</div>
		</div>
		<div class="box">
			<div style="height: 200px; background-color: red;">2</div>
		</div>
		<div class="box">
			<div style="height: 100px; background-color: gray;">3</div>
		</div>
		<div class="box">
			<div style="height: 500px; background-color: blue;">4</div>
		</div>
		<div class="box">
			<div style="height: 200px; background-color: yellow;">5</div>
		</div>
		<div class="box">
			<div style="height: 300px; background-color: gold;">6</div>
		</div>
		<div class="box">
			<div style="height: 100px; background-color: aquamarine;">7</div>
		</div>
	</div>
</body>

css

<style>
	#main {
		position: relative;
		margin: 0 auto;
	}

	.box {
		width: 200px;
		padding: 10px;
	}
	.box>div {
		padding: 10px;
	}
</style>

js

<script>
	function waterFall() {
		const boxes = document.getElementsByClassName('box')
		const length = boxes.length
		const boxWidth = boxes[0].offsetWidth
		const bodyWidth = document.body.clientWidth
	
		// 计算展示多少列
		const cols = parseInt(bodyWidth / boxWidth)
	
		// 主容器样式添加了margin:0 auto,现在设置主容器的宽度,让它居中对齐
		const mainDom = document.getElementById('main')
		mainDom.style.width = cols*boxWidth + 'px'
	
		// 数组用于存放每一列的高度
		const heightArr = []
	
		for (let index = 0; index < length; index++) {
			const box = boxes[index]
			const boxHeight = box.offsetHeight
	
			// 第一行
			if (index < cols) {
				heightArr[index] = boxHeight
	
				box.style.position = 'absolute'
				box.style.left = index * boxWidth + 'px'
				box.style.top = '0px'
	
			} else { // 第二行及以上
				// 找出高度最小的那一列,将当前box排在这一列
				const minBoxHeight = Math.min(...heightArr)
				const minBoxIndex = heightArr.indexOf(minBoxHeight)
			
				box.style.position = 'absolute'
				box.style.left = minBoxIndex*boxWidth + 'px'
				box.style.top = minBoxHeight + 'px'
	
				// 这一列排入当前box后,增加当前box的高度
				heightArr[minBoxIndex] += box.offsetHeight
			}
		}
	}		

	// 等整个页面渲染完成,图片等资源加载完成
	window.onload = function () {
		waterFall()
	}
	
	window.onresize = function () {
		waterFall()
	}
</script>

展示

瀑布流布局

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值