我正在尝试使用jquery构建一个砌体样式布局和位置元素。迭代元素时,我试图重置列位置一旦行变为3列宽但这段代码不起作用我不明白为什么
var rowPos = 0;
$(document).ready(function(){
$('.box').each(function(ind){
var elementWidth = $(this).width();
var elementHeight = $(this).height();
$(this).css({
left: rowPos +'px'
});
if(rowPos >= elementWidth * 2){
rowPos === 0;
}else{
rowPos += elementWidth;
}
console.log(rowPos);
});
});
这导致3列宽,其他元素堆叠在第三列之上。
CSS
body{
font-size: 20px;
}
.container{
position: relative;
}
.box{
width: 33.333%;
position: absolute;
color: #fff;
text-align: center;
box-sizing: border-box;
}
.box span{
margin-top: -1em;
position: relative;
top: 50%;
margin-top: -1em;
}
.box1, .box3, .box6, .box8{
height: 400px;
}
.box2, .box5{
height: 600px;
}
.box4, .box7{
height: 350px;
}
.container div:nth-child(odd){
background: #2a8d6f;
}
.container div:nth-child(even){
background: #5b3eac;
}
标记
<div class="container">
<div class="box box1"><span>box 1</span></div>
<div class="box box2"><span>box 2</span></div>
<div class="box box3"><span>box 3</span></div>
<div class="box box4"><span>box 4</span></div>
<div class="box box5"><span>box 5</span></div>
<div class="box box6"><span>box 6</span></div>
<div class="box box7"><span>box 7</span></div>
<div class="box box8"><span>box 8</span></div>
</div>
答案 0 :(得分:1)
我认为应该是
if(rowPos >= elementWidth * 2){
rowPos = 0; //not rowPos === 0;
}else{
rowPos += elementWidth;
}
答案 1 :(得分:0)
请看一下这种方法。能够管理盒子的最高位置:
var rowPos = 0;
var counter = 0;
$(document).ready(function() {
$('.box').each(function(ind) {
var elementWidth = $(this).width();
var elementHeight = $(this).height();
var height = 0;
var top = 0;
if (ind >= 3) {
var topBox = $('.box').eq(ind - 3);
height = topBox.height();
top = topBox.position().top;
}
$(this).css({
left: rowPos + 'px',
top: (height + top) + 'px'
});
if (counter >= 2) {
rowPos = 0;
counter = 0;
} else {
rowPos += elementWidth;
counter++;
}
});
});
body {
font-size: 20px;
}
.container {
position: relative;
}
.box {
width: 33.333%;
position: absolute;
color: #fff;
text-align: center;
box-sizing: border-box;
}
.box span {
margin-top: -1em;
position: relative;
top: 50%;
margin-top: -1em;
}
.box1,
.box3,
.box6,
.box8 {
height: 400px;
}
.box2,
.box5 {
height: 450px;
}
.box4,
.box7,
.box9 {
height: 350px;
}
.container div:nth-child(odd) {
background: #2a8d6f;
}
.container div:nth-child(even) {
background: #5b3eac;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<div class="container">
<div class="box box1"><span>box 1</span>
</div>
<div class="box box2"><span>box 2</span>
</div>
<div class="box box3"><span>box 3</span>
</div>
<div class="box box4"><span>box 4</span>
</div>
<div class="box box5"><span>box 5</span>
</div>
<div class="box box6"><span>box 6</span>
</div>
<div class="box box7"><span>box 7</span>
</div>
<div class="box box8"><span>box 8</span>
</div>
<div class="box box9"><span>box 9</span>
</div>
</div>