欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

js瀑布流(写死3列)

程序员文章站 2022-07-13 22:25:22
...
.imgBox {
    position: relative;
    width: 660px;
    margin: 0 auto;
  }

  .imgBox img {
    position: absolute;
  }
<div class="imgBox">
    <img src="../images/1.png" alt="">
    <img src="../images/nav.jpg" alt="">
    <img src="../images/icon2.png" alt="">
    <img src="../images/wx.png" alt="">
    <img src="../images/3.png" alt="">
    <img src="../images/精灵图.jpg" alt="">
    <img src="../images/question.png" alt="">
    <img src="../images/quan-arr.gif" alt="">
    <img src="../images/2.png" alt="">
    <img src="../images/搜索.png" alt="">
    <img src="../images/2.png" alt="">
  </div>
var imgBox = document.querySelector('.imgBox')
    var imgList = imgBox.children
    var firstLine = []
    var secondLine = []
    var thirdLine = []
    var marTop = 10
    var marLeft = 10
    for (let i = 0; i < imgList.length; i++) {
      imgList[i].style.width = imgBox.offsetWidth / 3 - 20 + 'px'
      if (i % 3 == 0) {
        firstLine.push(imgList[i])
      } else if (i % 3 == 1) {
        secondLine.push(imgList[i])
      } else {
        thirdLine.push(imgList[i])
      }

    }
    for (let j = 0; j < firstLine.length; j++) {
      if (j > 0) {
        firstLine[j].style.top = firstLine[j - 1].offsetTop + firstLine[j - 1].offsetHeight + marTop + 'px'
      }
    }
    for (let j = 0; j < secondLine.length; j++) {
      secondLine[j].style.left = secondLine[j].offsetWidth + marLeft + 'px'
      if (j > 0) {
        secondLine[j].style.top = secondLine[j - 1].offsetTop + secondLine[j - 1].offsetHeight + marTop + 'px'
      }
    }
    for (let j = 0; j < thirdLine.length; j++) {
      thirdLine[j].style.left = thirdLine[j].offsetWidth * 2 + marLeft * 2 + 'px'
      if (j > 0) {
        thirdLine[j].style.top = thirdLine[j - 1].offsetTop + thirdLine[j - 1].offsetHeight + marTop + 'px'
      }
    }