代码之家  ›  专栏  ›  技术社区  ›  Tzar

动画整页滚动按钮单击使用动画增强

  •  0
  • Tzar  · 技术社区  · 6 年前

    我想通过单击,以整个视图的宽度平滑地动画页面部分的水平滚动 Previous Page Next Page 按钮,使用 Animate Plus .

    以下是相关代码:

    import animate from "https://cdn.jsdelivr.net/npm/animateplus@2/animateplus.js"
    
    const previousPage = document.querySelector("button:nth-of-type(1)")
    const nextPage = document.querySelector("button:nth-of-type(2)")
    
    previousPage.addEventListener("click", () => {
      window.scrollBy(-window.innerWidth, 0)
      animate({
        easing: "out-quintic"
      })
    })
    
    nextPage.addEventListener("click", () => {
      window.scrollBy(window.innerWidth, 0)
      animate({
        easing: "out-quintic"
      })
    })
    

    我的完整代码可以在这里找到:

    https://codepen.io/anon/pen/bzVGMz


    我想要达到的动画效果可以在这里找到:

    http://animateplus.com/examples/anchor-scroll/

    我错过了什么?

    1 回复  |  直到 6 年前
        1
  •  1
  •   jo_va    6 年前

    其思想是使用变更回调并计算一个增量来滚动窗口。这个增量等于进度乘以我们想要滚动的距离。

    不过,我想你希望 只使用“上一个”和“下一个”按钮浏览多个部分 . 自从 用户还可以手动滚动 对于不同的部分,您需要一种方法来检测当前在视图中的部分,并通过编程转到上一个/下一个部分。

    下面的代码通过维护按左坐标排序的部分列表来实现这一点。 对于这个例子,我认为当前部分是跨越屏幕中心线的部分。

    import animate from "https://cdn.jsdelivr.net/npm/animateplus@2/animateplus.js"
    
    const previousPage = document.querySelector("button:nth-of-type(1)")
    const nextPage = document.querySelector("button:nth-of-type(2)")
    
    const root = document.scrollingElement;
    
    const sections = Array.from(document.querySelectorAll("section")).sort((s1, s2) => {
      return s1.getBoundingClientRect().left - s2.getBoundingClientRect().left;
    });
    
    // get the section that spans the centerline
    const getSectionInView = () => {
      const halfWdidth = window.innerWidth / 2;
      const index = sections.findIndex(s =>
        s.getBoundingClientRect().left <= halfWdidth &&
        s.getBoundingClientRect().right > halfWdidth
      );
      return index;
    };
    
    // find the next or previous section in the list
    const getNextSection = (dir) => {
      const sectionInViewIndex = getSectionInView();
      const nextIndex = sectionInViewIndex + dir;
      const numSections = sections.length;
      const nextSectionIndex = nextIndex < 0 || nextIndex >= numSections ? sectionInViewIndex : nextIndex;
      return sections[nextSectionIndex];
    };
    
    // animation function
    const animateScroll = (dir) => {
      const from = root.scrollLeft;
      const { left } = getNextSection(dir).getBoundingClientRect();
      return progress => root.scrollLeft = from + progress * left
    };
    
    previousPage.addEventListener("click", () => {
      animate({
        easing: "out-quintic",
        change: animateScroll(-1)
      });
    });
    
    nextPage.addEventListener("click", () => {
      animate({
        easing: "out-quintic",
        change: animateScroll(1)
      });
    });
    

    这里是一个 CodePen

    为了工作,你必须移除 scroll-snap-align: center; section 样式或设置为 none 因为它与动画冲突。