Published on

抖音上滑切换,每页div可竖直滚动(React)

Authors

正文 需要实现的效果:

需要实现的效果

实现方法:嵌套swiper+让第二层的slider不能滑动,然后聊天记录放第二层slider里 为什么这样做:里层swiper在捕获到div里的touch不会滑动,而在外层swiper里只能拿到“里层swiper是否滑动”的信息

实现思路
// Import Swiper React components
import { Swiper, SwiperSlide } from "swiper/react";
// import required modules
import { Pagination } from "swiper/modules";

export default function App() {
  return (
    <>
      <Swiper
        direction={"vertical"}. //竖向slider
        pagination={{
          clickable: true,
        }}
        modules={[Pagination]}
        className="mySwiper"
      >
        <SwiperSlide>
          <Swiper nested={true} freeMode={true} className="swiper-nested"> // 内层swiper,注意设置他的hight和宽度
            <SwiperSlide className="swiper-no-swiping">  //这里加swiper-no-swiping让slider无法滚动
              <Message /> //需要滚动的div
            </SwiperSlide>
          </Swiper>
        </SwiperSlide>
        <SwiperSlide>Slide 2</SwiperSlide>
        <SwiperSlide>Slide 3</SwiperSlide>
      </Swiper>
    </>
  );
}

".swiper .swiper-slide会被swiper自动捕获,写 SwiperSlide className="swiper-no-swiping""会让此slide无法滚动,swiper-no-swiping被看作为“通过css传递的内置参数”

注意里层swiper的面积要小于外层swiper的面积

function Message() {
  const arr = new Array(50).fill(0);
  return (
    <div className="message-container ">
      {arr.map((item, i) => {
        return <div>{i}</div>;
      })}
    </div>
  );
}
//css
.swiper {
  width: 100%;
  height: 100%;
}

.swiper-nested {
  width: auto;
  height: auto;
}
.swiper-slide {
  text-align: center;
  font-size: 18px;
  background: #fff;

  /* Center slide text vertically */
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: space-between;
}

仓库:https://github.com/Wsgamer7/swiper_test

演示地址:https://swiper-test-henna.vercel.app/ 用手机打开