The first and last two items of swiper are not centered and the remaining items are centered

In the use of swiper, there is a scene where the first and last two items are displayed to the left or right, and the remaining items are displayed in the center, as shown in the figure:
Insert picture description here
Insert picture description here
Insert picture description here
If all items are centered and part of the adjacent items are exposed, you can directly set as follows:

const settings = {
    
    
  // 两遍显示相邻两张
  slidesPerView: 'auto',

  // 相邻两张间距
  spaceBetween: 12,

  // swiper动态加载
  observer:true, 
  observeParents:true,

  // 当前页居中显示
  centeredSlides: true,
}

The first and last two welts, you can add a parameter:

const settings = {
    
    
  // 两遍显示相邻两张
  slidesPerView: 'auto',

  spaceBetween: 12,

  // swiper动态加载
  observer:true, 
  observeParents:true,

  // 当前页居中显示
  centeredSlides: true,

  // 第一张和最后一张贴合边缘 
  centeredSlidesBounds: true, 
}

Then in the component new Swiper:

  useEffect(() => {
    
    
      let mySwiper = new Swiper('.swiper-container', settings);
      mySwiper.on('slideChange',hanldeSlide)
      return ()=>{
    
    
        mySwiper.destroy();
      }
  }, []);

You need to set the width of the .swiper-wrapper to 100%, and the width of the sliding block. The
effect after setting the swiper-slide is this: you
Insert picture description here
need to add a left margin and a right margin to the first and last two pieces:

      .first-last-slide:first-of-type{
    
    
        margin-left: 38px;
      }
      .first-last-slide:last-of-type{
    
    
        margin-right: 38px;
      }
      .swiper-slide{
    
    
        width: 610px;
      } 

One thing to note is that if the component gets the data in the swiper after the new Swiper, such as relying on the interface or props, the following two parameters must be set to true, otherwise all sliding items will exist when viewing the element. , But only the first one is actually slideable on the page:

  observer:true, 
  observeParents:true,

Guess you like

Origin blog.csdn.net/dhw276/article/details/113271447