javascript - 使用 Animate Plus 在按钮单击时动画整页滚动
问题描述
我想通过单击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"
})
})
我的完整代码可以在这里找到:
我想实现的动画效果可以在这里找到:
我错过了什么?
解决方案
这个想法是使用更改回调并计算滚动窗口的增量。这个增量等于进度乘以我们想要滚动的距离。
但是,我假设您希望能够仅使用 prev 和 next 按钮浏览多个部分。由于用户还可以手动滚动到不同的部分,因此您需要一种方法来检测当前正在查看的部分并以编程方式转到上一个/下一个。
下面的代码通过维护一个按左坐标排序的部分列表来做到这一点。对于此示例,我将当前部分视为跨越屏幕中心线的部分。
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
为与动画冲突。
推荐阅读
- javascript - 使用 NgRx 和 Kendo UI (Angular) 上传组件在 formState 中编辑时如何传递(设置)文件字符串数据?
- reactjs - 与 React Router 链接时如何传递函数?
- python - 模块导入错误,使用 Google Colab
- python - 如何修复“TypeError:'int' 对象在 rfind(os.sep.path) + 1 中不可下标:”
- angular - 如何在上一个 api 请求在 ionic 中完成后发出 api 请求
- java - Tika Parser 无法解析希腊字符
- ajax - RAILS 6 Ajax 事件和 Ajax Spinner
- javascript - 如何在useEffect中处理获取的数据
- java - 如何在 Java 8 中格式化 ZoneDateTime?
- javascript - 如何使用 react 和 javascript 修复输入验证电子邮件的正则表达式?