Realization of waterfall flow with native js and Realization of waterfall flow with left and right columns in wechat applet

Keywords: Front-end Fragment iOS Android

It is not practical to use css to realize waterfall flow, because the waterfall flow realized in Chaoshan city is arranged in columns. Here, we record the realization of waterfall flow with js and the realization of waterfall flow with left and right columns in wechat applet

1. effect picture

2. Native js realizes waterfall flow

  • html file
<div id="root">
    <div class="item">
        <div class="itemImg">
            <img src="../images/1.jpeg" alt="" />
        </div>
    </div>
    <div class="item">
        <div class="itemImg">
            <img src="../images/3.jpeg" alt="" />
        </div>
    </div>
    <div class="item">
        <div class="itemImg">
            <img src="../images/2.jpg" alt="" />
        </div>
    </div>
</div>
  • You can replace the picture by yourself
  • css file
*{
    margin: 0;
    padding: 0;
}
#root{
    position: relative;
}
.item{
    float: left;
    padding: 5px;
}
/* When adding shadows, the border will be more suspended */
.itemImg{
    padding: 5px;
    border: 1px solid #ccc;
    box-shadow: 0 0 5px #ccc;
    border-radius: 5px;
}
.itemImg img{
    width: 230px;
    height: auto;
}
  • js file
window.onload = function () {

    /* Calculate the number of picture columns and get the minimum height picture */
    generateImg('root', 'item');

    /* Monitor for window size changes, and re layout for size changes */
    window.addEventListener('resize', function() {
        generateImg('root', 'item')
    });

    /* Picture object */
    let imgData = {
        images: [
            {
                "src":"23.png"
            },
            {
                "src":"22.png"
            },
            {
                "src":"2.jpg"
            },
            {
                "src":"4.jpg"
            },
            {
                "src":"7.jpg"
            }
        ]
    };
    /* Monitor scrolling */
    window.addEventListener('scroll', function() {
        if(checkIsScroll()) {
            let rootElement = document.getElementById('root');
            /* Using document fragment to create */
//                    let documentFragment = document.createDocumentFragment();
            let length = imgData.images.length;

            /* Cycle through picture groups */
            for(let i = 0; i < length; i++) {
                let itemElement = document.createElement('div');
                itemElement.className = 'item';
                rootElement.appendChild(itemElement);
                let itemImgElement = document.createElement('div');
                itemImgElement.className = 'itemImg';
                itemElement.appendChild(itemImgElement);
                let itemImg = document.createElement('img');
                itemImg.style.cssText = 'opacity: 0; transform:scale(0)';
                itemImg.src = "../images/" + imgData.images[i].src;
                itemImgElement.appendChild(itemImg);
//                        documentFragment.appendChild(itemElement);

                /* Let the picture show in one second */
                (function(img){
                    setTimeout(function(){
                        img.style.cssText="opacity:1;transform:scale(1)";
                    },1000);
                })(itemImg);
            }
//                    rootElement.appendChild(documentFragment);
            generateImg('root', 'item');
        }
    });
};

/* Calculate the number of picture columns and get the minimum height picture */
function generateImg(parent, content) {
    /* Get parent element and all node contents */
    let parentElement = document.getElementById(parent);
    let childContent = getChildElement(parentElement, content);

    /* Get picture width */
    let imgWidth = childContent[0].offsetWidth;
    /* Get the number of columns formed by a row of pictures */
    let imgColumn = Math.floor(document.documentElement.clientWidth / imgWidth);
    /* Reset the width of the parent container */
    parentElement.style.cssText = 'width:' + imgColumn * imgWidth + 'px;margin:0 auto';

    /* Store the height of each picture to find the minimum picture height */
    let imgHeightArray = [];
    let length = childContent.length;
    for(let i = 0; i < length; i++) {
        /* i<imgColumn Count the height of each line */
        if(i < imgColumn) {
            /* Prevent users from changing the window size and content style disorder */
            childContent[i].style.cssText = '';
            imgHeightArray.push(childContent[i].offsetHeight);
        } else {
            /* If not on this line, find the index values for the minimum and minimum values */
            let minHeight = getMinImgHeight(imgHeightArray);
            let minHeightIndex = getMinHeightIndex(imgHeightArray, minHeight);
            /* Set the location for this picture */
            childContent[i].style.position = 'absolute';
            childContent[i].style.top = minHeight + 'px';
            childContent[i].style.left = childContent[minHeightIndex].offsetLeft + 'px';
            /* Replace the minimum height at this time */
            imgHeightArray[minHeightIndex] = childContent[i].offsetHeight + minHeight;
        }
    }
}

/* Check whether the scrolling reaches the visual area */
function checkIsScroll() {
    /* Get root node */
    let parentElement = document.getElementById('root');
    /* Get the element node whose class name is box under the parent element */
    let childContent = getChildElement(parentElement, 'item');

    /* Get the height of the last element */
    let lastElementHeight = childContent[childContent.length - 1].offsetTop;
    /* Get rolling distance */
    let scrollTopSpace = document.documentElement.scrollTop || document.body.scrollTop;
    /* Get the distance of visual area */
    let clientHeight = document.documentElement.clientHeight || document.body.clientHeight;

    if(lastElementHeight > scrollTopSpace + clientHeight) {
        return true;
    }
}
/* Get all the contents of a child node */
function getChildElement(parentElement, content) {
    /* Store element information */
    let elementArray = [];
    /* Get all node information under the parent element */
    let allElement = parentElement.getElementsByTagName('*');
    let length = allElement.length;
    for (let i = 0; i < length; i++) {
        /* Find the corresponding class name */
        if (allElement[i].className === content) {
            elementArray.push(allElement[i]);
        }
    }
    return elementArray;
}

/* Get minimum height of picture */
function getMinImgHeight(heightArray) {
    let length = heightArray.length;
    let minHeight = heightArray[0];
    for(let i = 0; i < length; i++) {
        minHeight = Math.min(minHeight, heightArray[i]);
    }
    return minHeight;
}

/* Get the index value of the minimum height of the picture */
function getMinHeightIndex(heightArray, minHeight) {
    let length = heightArray.length;
    for(let i = 0; i < length; i++) {
        if(heightArray[i] == minHeight) {
            return i;
        }
    }
}

3. Realizing waterfall flow in wechat applet

  • Design sketch

  • wxml file
<view class="cateCommodity">
  <view class="leftContainer">
    <block wx:for="{{imageArray}}" wx:key="{{item.id}}">
      <view class="cateItem" wx:if="{{index%2==0}}">
        <view class="item">
          <image src="{{item.src}}" class="itemImg" mode="widthFix"></image>
          <view class="title">{{item.title}}</view>
        </view>
      </view>
    </block>
  </view>
  <view class="rightContainer">
    <block wx:for="{{imageArray}}" wx:key="{{item.id}}">
      <view class="cateItem" wx:if="{{index%2==1}}">
        <view class="item">
          <image src="{{item.src}}" class="itemImg" mode="widthFix"></image>
          <view class="title">{{item.title}}</view>
        </view>
      </view>
    </block>
  </view>
</view>
<view class="skipTop" catchtap="skipTop" wx:if="{{showTopImage}}">
  <image src="http://boweisou.oss-cn-shenzhen.aliyuncs.com/images/0/2018/11/ZBtqujbbcGjBDgjt0bbJqbTuGqq0z8.png"></image>
</view>
  • wxss file
page{
  background: #f6f6f6;
}
/* Outermost layer */
.cateCommodity {
  display: flex;
  padding: 20rpx 28rpx 8rpx;
  box-sizing: border-box;
  font-size: 28rpx;
}
/* Left and right containers */
.leftContainer{
  display: flex;
  margin-right: 22rpx;
  flex-direction: column;
}
.rightContainer{
  display: flex;
  flex-direction: column;
}
/* Picture container */
.cateItem {
  margin-bottom: 20rpx;
}
.item{
  padding: 20rpx 22rpx;
  width: 335rpx;
  box-sizing: border-box;
  background: #fff;
  border-radius: 6rpx;
}
.itemImg{
  margin-bottom: 14rpx;
  width: 100%;
  vertical-align: middle;
  border-radius: 6rpx;
}
.title{
  display: -webkit-box;
  overflow: hidden;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
  line-height: 1.5;
}
/* Return to the top */
.skipTop {
  position: fixed;
  bottom: 30rpx;
  right: 20rpx;
  width: 90rpx;
  height: 90rpx;
}

.skipTop image {
  width: 100%;
  height: 100%;
  vertical-align: middle;
}
  • js file
Page({
  data: {
    imageArray: [
      {
        id: 1,
        src: '../../images/avatar.jpeg',
        title: 'Modern new Chinese creative ceramics simple decoration living room living room porch soft decoration home wine cabinet plate'
      },
      {
        id: 1,
        src: '../../images/avatar3.jpg',
        title: 'Autumn and winter new 2018 leisure sportswear set women's Korean version of gold velvet sweater plus Plush two-piece set'
      },
      {
        id: 1,
        src: '../../images/avatar4.jpeg',
        title: 'Girls' bedding 4-piece Princess Room 1.2m Bed product pure cotton girl 1.8 Children's bed sheet three piece set 1.5'
      },
      {
        id: 1,
        src: '../../images/avatar7.jpg',
        title: 'Round bed bed bed bed bed bed net landing type baby oval bed bed bed bed bed net support type child bed bed net BB Bed nets'
      },
      {
        id: 1,
        src: '../../images/avatar9.jpeg',
        title: 'Dynamic package 158 T Speed skates, roller skates, racing shoes, high-end carbon fiber shoes, fixed size, professional customization'
      },
      {
        id: 1,
        src: '../../images/logo7.jpg',
        title: 'Infanton Landing crib mosquito net with bracket children's bed mosquito net baby's mosquito net baby's mosquito net'
      },
      {
        id: 1,
        src: '../../images/logo6.jpg',
        title: 'old A Height of roller skating seba hl Carbon fiber version SEBA HL CARBON Flat shoes, brake shoes, all-around shoes'
      },
      {
        id: 1,
        src: '../../images/logo.jpeg',
        title: 'Yangyang legal system sandro 17 Autumn and winter one button wool long overcoat EKIN M9575H'
      },
    ],
    showTopImage: false,
  },
  onPageScroll(event) {
    /* Using two conditions to prevent repeated setData operations */
    if (event.scrollTop > 300 && this.data.showTopImage == false) {
      this.setData({
        showTopImage: true
      })
    } else if (event.scrollTop < 300 && this.data.showTopImage == true) {
      this.setData({
        showTopImage: false
      })
    }
  },
  skipTop() {
    /* Return to the top */
    wx.pageScrollTo({
      scrollTop: 0,
      duration: 300
    });
    this.setData({
      showTopImage: false
    });
  },
  onReachBottom: function () {
    let temporaryArray = this.data.imageArray;
    temporaryArray.push(...this.data.imageArray);
    this.setData({
      imageArray: temporaryArray
    })
  },
})
  • To realize waterfall flow in the left and right columns is to render the same array twice, but hide half of it

Studying hard. If it helps your study, leave your mark

Posted by grandman on Mon, 02 Dec 2019 18:22:07 -0800