利用css解决轮播图的横向滚动问题

207 阅读1分钟
业务要求:轮播图横向滚动时,保证无论如何滑动都是整页展示,轻微滑动时,可以回弹,当前轮播页展示时,可以露出部分下一张轮播页,有切换按钮可左右切换

react项目

利用css属性:scroll-snap-type/scroll-snap-align,具体概念在mdn自行查看

scroll-snap-type:滚动容器的下吸附至吸附点的严格程度

scroll-snap-align:当前元素在滚动容器的吸附位置,即设置scroll-snap-type的容器。

具体实现:

.pcContainer {
  display: flex;
  overflow: auto hidden;
  width: 100%;
  height: 500px;
  flex-flow: row nowrap;
  scroll-snap-type: x mandatory;
}

.sliderWrap{
  scroll-snap-align: start;
}
// 轮播宽度= 屏幕宽度 - 轮播图间距 -下一张轮播的露出宽度
const cardSize = window.innerWidth - padding -sideShowWidth
// 切换轮播回调
const updateCarousel = (sign: number) => {
    const { scrollLeft } = pcSwiperRef.current || {};
    const tempIndex = Math.round(scrollLeft / window.innerWidth) + sign;

    let nextIndex = tempIndex;
    if (tempIndex < 0) {
      nextIndex = swiperList.length - 1;
    } else if (tempIndex >= swiperList.length) {
      nextIndex = 0;
    }
    const newPosition = nextIndex * cardSize;
    pcSwiperRef.current.scrollTo({
      left: newPosition,
      behavior: 'smooth'
    });
}

<div className='activeCtrl' onClick={() => updateCarousel(-1)}>&lt;</div>
<div className='activeCtrl' onClick={() => updateCarousel(1)}>&gt;</div>
  
<div className="pcContainer" ref={pcSwiperRef}>
      {swiperList.map((item: string[], index: number) => {
        return <div key={index} className='sliderWrap' style={{
          width: cardSize,
          marginRight: index === (swiperList.length - 1) ? padding : 0,
          paddingLeft: padding,
        }}>
           <Image key={url} src={url}
            style={{
              height: '100%',
              width:  '100%',
            }}
        />
        </div>
      })}
</div>