javascript - 仅在视口中进行动画处理
问题描述
我正在尝试采用以下技术:
https://codepen.io/donovanh/pen/rmzNZJ
到一个学习项目,但我不确定我做错了什么。我在这里上传了我自己项目的部分内容:
https://codepen.io/cucurutcho/pen/KKWRrov
基本上,当元素在屏幕上可见时,JS 正在努力向元素添加自定义类,因此对其进行一些动画处理。但是在我的示例中,没有添加类,我不知道为什么,我可能在这里遗漏了一些超级简单的东西,但是任何可以阐明的人都非常感谢!为了更容易,在我的代码笔(第二个)上,您可以看到具有“滚动显示”类的元素不像在第一个代码笔上那样工作,我从中获得了技术。这是应该执行此操作的 JS 代码:
// Detect request animation frame
var scroll = window.requestAnimationFrame ||
// IE Fallback
function(callback){ window.setTimeout(callback, 1000/60)};
var elementsToShow = document.querySelectorAll('.show-on-scroll');
function loop() {
Array.prototype.forEach.call(elementsToShow, function(element){
if (isElementInViewport(element)) {
element.classList.add('is-visible');
} else {
element.classList.remove('is-visible');
}
});
scroll(loop);
}
// Call the loop for the first time
loop();
// Helper function from: http://stackoverflow.com/a/7557433/274826
function isElementInViewport(el) {
// special bonus for those using jQuery
if (typeof jQuery === "function" && el instanceof jQuery) {
el = el[0];
}
var rect = el.getBoundingClientRect();
return (
(rect.top <= 0
&& rect.bottom >= 0)
||
(rect.bottom >= (window.innerHeight || document.documentElement.clientHeight) &&
rect.top <= (window.innerHeight || document.documentElement.clientHeight))
||
(rect.top >= 0 &&
rect.bottom <= (window.innerHeight || document.documentElement.clientHeight))
);
}
解决方案
推荐阅读
- python - 在 CyLP 中初始化整数变量
- arrays - ESC POS Epson 热敏打印机使用 Swift 打印图像
- swift - 这个 RealityKit 的东西是构思不好还是我错过了什么?
- python - 隐藏数据库密码python
- javascript - 如何使NODE在公共IP地址网站上工作?
- typescript - TypeScript:将对象条目映射到类型
- tsql - 如何截断/清空巨大的 SQL 日志文件
- javascript - 让导航栏在 React 中工作。通过道具向孩子发送功能?
- c++ - 如果将“HTML 格式”用于电子邮件,那么使用 SetClipboardData 将表格数据放入剪贴板是否是正确的格式?
- java - 如何延长 Oauth 2 StoredCredential 的持续时间