swiper will repeat the solution when the amount of data in the loop mode is less than the value of slidesPerView

# Repeatedly appear when the amount of data in loop mode is less than the value of slidesPerView, as shown in the following figure

4.jpg

# We need to render and initialize the swiper according to the data returned in the background, code implementation

## html+css code

// html
<div class="container">
  <div class="left">
    <div class="up">
      <div class="swiper-container swiper-container-vertical s1">
        <div class="swiper-wrapper">
        </div>
      </div>
    </div>
    <div class="down"></div>
  </div>
  <div class="right"></div>
</div>
// css
* {
  margin: 0;
  padding: 0;
  box-sizing: border-box;
}

html,
body {
  height: 100%;
}

.container {
  height: 100%;
  display: flex;
}

.container>div {
  flex: 1;
}

.container .left>div {
  height: 50%;
}

.container .left .up {
  background: #ccc;
}

/*This code cannot be less, that is, the height must be specified for the swiper-container, which is the same height as its own parent*/
.s1 {
  height: 100%;
}

.s1 .swiper-wrapper {
  /* flex-direction: column; */
}

.s1 .swiper-wrapper>div {
  /* height: calc(100% / 4); */
}


## Core code description

5.jpg

## js code

let swiper1;
let data = [];

$(function () {
  // 1. Get data
  getData()
  // 2. Rendering world
  initUI ()
  if (data.length > 4) {
    // 3. Initialize swiper
    initSwiper()
  } else {
    // Get the height of the parent
    let h = $('.swiper-wrapper').height() / 4
    // Find the height of each swipe-slide
    $('.s1 .swiper-wrapper .swiper-slide').css('height', h)
  }
})

function getData() {
  // Control the amount of data in this place
  for (let i = 0; i < 5; i++) {
    data.push(i)
  }
}

function initUI() {
  let html = ''
  data.forEach((item, index) => {
    let color = index % 2 ? '#1acd7e' : '#fb3'
    html += `<div class="swiper-slide" style="background: ${color}">${item}</div>`
  })
  $('.s1 .swiper-wrapper').html(html)
}

function initSwiper() {
  swiper1 = new Swiper('.s1', {
    autoplay: true,
    slidesPerView: '4', // display a few in the display area
    direction: 'vertical',
    loop: true,
  })
}

## Core code description

6.jpg

When the number of data is insufficient, it is recommended to use js to calculate the height of each swiper-slide

# to sum up

1. In the loop mode, the data will be repeated when the amount of data is less than the value of slidesPerView. You need to add a judgment. When the data is not enough, you can not initialize the swiper, then you need to manually set the height of each swimer-slide at this time


Guess you like

Origin blog.51cto.com/11871779/2550233