javascript - 如何更改我的代码以使项目在滚动一次后保持可见?
问题描述
如何更改我的代码以使项目在滚动一次后保持可见?我是一个真正的编码初学者,所以欢迎任何帮助和提示。提前谢谢你的帮助!
.inline-photo {
opacity: 0;
transform: translateY(60px) ;
transition: transform 3000ms 500ms cubic-bezier(0,1,.3,1),
opacity 300ms 500ms ease-out;
will-change: transform, opacity;
}
.inline-photo.is-visible {
opacity: 1;
transform: rotateZ(0deg);
}
var scroll = window.requestAnimationFrame ||
function(callback){ window.setTimeout(callback, 1000/60)};
var elementsToShow = document.querySelectorAll('.show-on-scroll');
function loop() {
elementsToShow.forEach(function (element) {
if (isElementInViewport(element)) {
element.classList.add('is-visible');
} else {
element.classList.remove('is-visible');
}
});
scroll(loop);
}
loop();
function isElementInViewport(el) {
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))
);
}
我的最终目标是在它们出现一次后让其保持可见。
解决方案
在 CSS 中将逻辑与设备分开。
创建一个应用可见性的类。
.inline-photo.is-shown {
opacity: 1;
transform: rotateZ(0deg);
}
并让is-visible
管理代码中的状态。
if (isElementInViewport(element)) {
element.classList.add('is-visible', 'is-shown');
} else {
element.classList.remove('is-visible');
}
推荐阅读
- json - 如何生成包含两个数组的副本?
- python-3.x - 如何查看 sockets 或 pyHook 等模块的代码(类和方法)?
- javascript - 文本框值未更新
- arrays - 如何从 MongoDB 的子文档数组中只返回一个匹配的子文档(不是数组)?
- android - Android:如何将所有子列表从 Firebase 获取到 arraylist
- javascript - 使用 javaScript 更改背景颜色(请不要使用 jQuery)?
- python - Glade:尝试删除列表存储行时的差异
- google-apis-explorer - 更新架构 Api 出错 - Google 云搜索
- dialogflow-es - DialogFlow - 从 webhook 设置 allRequiredParamsPresent?
- python - 如何将 Python 脚本中的字典列表导入 Ansible 剧本?