九宫格布局
有些网站图片展示都是几行几列排列,开发者可以用九宫格布局任意排列图片
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>九宫格布局</title>
<style>
*{
padding: 0;
margin: 0;
}
#wrap{
position: relative;
width: 100%;
}
.box{
background: #fd7600;
width: 480px;
height: 270px;
}
</style>
</head>
<body>
<button id="btn1">3列</button>
<button id="btn2">4列</button>
<button id="btn3">5列</button>
<div id="wrap">
<div class="box">
<img src="../images/a1.jpg" alt="">
</div>
<div class="box">
<img src="../images/a2.jpg" alt="">
</div>
<div class="box">
<img src="../images/a3.jpg" alt="">
</div>
<div class="box">
<img src="../images/a4.jpg" alt="">
</div>
<div class="box">
<img src="../images/a5.jpg" alt="">
</div>
<div class="box">
<img src="../images/a6.jpg" alt="">
</div>
<div class="box">
<img src="../images/a7.jpg" alt="">
</div>
<div class="box">
<img src="../images/a8.jpg" alt="">
</div>
<div class="box">
<img src="../images/a9.jpg" alt="">
</div>
<div class="box">
<img src="../images/a10.jpg" alt="">
</div>
<div class="box">
<img src="../images/a11.jpg" alt="">
</div>
<div class="box">
<img src="../images/a12.jpg" alt="">
</div>
</div>
<script src="../myTool.js"></script>
<script>
/*
通过子元素数量和自定义列数来确定每个子元素的坐标
* 从rows:0行cols:0列开始,每一个格子(下标n从0开始(左标(rows,cols))的距离上边距离
* top=(子盒子高度height)*rows+(边距y),左边的距离left=(子盒子width)*cols+(边距x)
* */
window.onload=function () {
let wrap=myTool.$("wrap")
myTool.$("btn1").onclick=function () {
j_flex(3,wrap)
}
myTool.$("btn2").onclick=function () {
j_flex(4,wrap)
}
myTool.$("btn3").onclick=function () {
j_flex(5,wrap)
}
}
function j_flex(allCols,parentNode) { //allCols自定义列数
let box=parentNode.children[0]
//获取子元素宽高
var boxw=box.offsetWidth
var boxh=box.offsetHeight
var marginxy=15
//遍历子元素
for(let i=0;i<parentNode.children.length;i++){
//求出当前盒子所在的行和列
let row=Math.floor(i/allCols)
let col=Math.floor(i%allCols)
//当前盒子的定位
let currentbox=parentNode.children[i]
currentbox.style.position="absolute"
currentbox.style.left=col*(boxw+marginxy)+"px"
currentbox.style.top=row*(boxh+marginxy)+"px"
}
}
</script>
</body>
</html>
若有仙鹤从旁骥,尽是人间第一流。