首页 > 解决方案 > 轮播,当父元素垂直滚动移动时让水平滚动结束移动

问题描述

我创建了一个类似于 Instagram 上正在运行的轮播,但我意识到如果我在子元素的滚动 x 移动结束之前移动父元素的滚动 y,它不会结束。

下面的例子的 gif ...

注意:抱歉英语不好,不是我的母语。

代码

.container {
  width: 100%;
  display: flex;
  flex-direction: column;
  overflow-y: scroll;
  .x {
    margin-top: 30px;
    display: flex;
    overflow-x: scroll;
    scroll-snap-type: x mandatory;
    div {
      flex: 0 0 auto;
      scroll-snap-align: start;
      width: 100vw;
      height: 100vw;
    }
    .x-item1 {
      background: green;
    }
    .x-item2 {
      background: blue;
    }
  }
}
<Container>
  <div className="x">
    <div className="x-item1" />
    <div className="x-item2" />
  </div>

  ... other divs
</Container>

--->> 示例 Gif !!<<---

标签: javascripthtmlreactjscarousel

解决方案


我找到了一个解决方案,在我看来,它可以满足我的建议,而不会失去功能的性能......

我只是认为scrollIntoView可能会有延迟,比如“行为:平滑”......

https://developer.mozilla.org/pt-BR/docs/Web/API/Element/scrollIntoView

但是如果有人想添加改进,它就不起作用了,谢谢。

在容器中我放了一个“onTouchStart”

<Container className="works" onTouchStart={() => handleCarousel()} >
  <div className="x">
    <div className="x-item1" />
    <div className="x-item2" />
  </div>

  ... other divs
</Container>

函数句柄轮播...

const handleCarousel = () => {
    const works = Array.from(document.querySelectorAll('.work-content'));
    const carousels = Array.from(document.querySelectorAll('.work-carousel'));
    carousels.forEach(carousel => {
      if (carousel.scrollLeft % window.innerWidth !== 0) {
        const item = document.querySelector(
          `.work-content:nth-child(${
            works.indexOf(carousel.parentElement) + 1
          }) > div.work-carousel > img.work-carousel-item-active`, 
        ); // in another function I already control which image is being viewed and add this class
        const scroll = document.querySelector('.works').scrollTop; // optional: get vertical scroll value
        item.scrollIntoView(); // horizontal scrolling gains focus
        document.querySelector('.works').scrollTop = scroll; // optional: returns vertical scroll value
      }
    });
  };

推荐阅读