js实现
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<style>
*{
padding: 0;
margin: 0;
list-style: none;
}
#box{
position: relative;
}
.smallbox {
background-color: #ccc;
position: absolute;
}
</style>
</head>
<body>
<button></button>
<div id="box">
</div>
<script>
window.onload=function(){
var box = document.getElementById('box');
change(5,25,200,200,5) //修改第一个从来参数可以调整列数
function change(col,boxlength,width,height,margin){
for(var i =0;i<boxlength;i++){
var small = document.createElement("div");
small.className='smallbox';
box.appendChild(small)
small.style.width=width + "px";
small.style.height=height+ 'px';
small.style.margin=margin+ 'px';
small.style.left = parseInt(i%col)*(width+margin) + "px";
small.style.top=parseInt(i/col)*(height+margin)+"px";
}
}
}
</script>
</body>
</html>
jq实现
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<script src="https://apps.bdimg.com/libs/jquery/2.1.4/jquery.min.js"></script>
<style>
*{
padding: 0;
margin: 0;
list-style: none;
}
#box{
position: relative;
}
.smallbox {
background-color: #ccc;
position: absolute;
}
</style>
</head>
<body>
<button id="btn1">生成俩列</button>
<div id="box">
</div>
<script>
$(function(){
var box = $('#box');
var width=100,height=100,margin=10,col=6; //改变col的值,可以改变列数
change(width,height,margin,col) //调用方法
function change(width,height,margin,col){
for(var i =0;i<30;i++){
var small = $('<div class="smallbox"></div>');
box.append(small);
small.css({"left":parseInt(i%col)*(width+margin)+ 'px',"width":width,'height':height,"top":parseInt(i/col)*(height+margin) + "px"});
}
};
})
</script>
</body>
</html>
vue实现九宫格布局
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<script src="https://cdn.staticfile.org/vue/2.2.2/vue.min.js"></script>
<style>
*{
padding: 0;
margin: 0;
list-style: none;
}
#box{
position: relative;
}
.smallbox {
background-color: #ccc;
position: absolute;
width: 100px;
height: 100px;
margin:100px;
}
</style>
</head>
<body>
<div id="box">
<button @click="change(3)">3列</button>
<button @click="change(4)">4列</button>
<button @click="change(5)">5列</button>
<button @click="change(6)">6列</button>
<div v-for="po in position" class="smallbox" :style="{left:po.left+'px',top:po.top+'px'}">{{po}}</div>
</div>
<script>
new Vue({
el:"#box",
data:{
width:"100px",
height:"100px",
position:[],
},
methods:{
change:function(col){
this.position=[]
for(var i =0;i<100;i++){
var l = parseInt(i%col)*(100+10);
var t = parseInt(i/col)*(100+10);
po={'left':l,"top":t}
console.log(po)
this.position.push(po)
}
}
}
})
</script>
</body>
</html>