我目前正在为学校制作自己的单页作品集网站,我有一个很酷的想法,我想通过使用进度条来展示我在某些编码语言中的进展程度,例如,c# = 60%,这将是圆的 60%。我想我可以使用互联网来做到这一点,但我希望当我向下滚动时它在 60 处开始/结束,并且当它在屏幕上时它应该启动进度条。我不知道也无法找到当(在本例中是进度条)在屏幕上可见时如何触发代码。
注意:我是一个相当新的 JavaScript 程序员和一个相当新的用户,所以请解释我是否做错了什么。
最佳答案
以下是使用 Intersection Observer API 滚动到图像高度的 75% 时触发动画的工作示例:
const images = document.querySelectorAll('.animate-me');
const config = {
root: null, // viewport
rootMargin: '0px',
threshold: 0.75
};
let observer = new IntersectionObserver(function(entries) {
entries.forEach(function(entry) {
if (entry.intersectionRatio >= config.threshold) {
entry.target.classList.add("active");
}
});
}, config);
images.forEach(image => {
observer.observe(image);
});
.spacer {
height: 400px;
}
.animate-me.active {
animation: anim1 .7s ease-out;
}
@keyframes anim1 {
0% {
transform: rotate(0deg);
}
100% {
transform: rotate(360deg);
}
}
<div class="spacer">(Scroll down)</div>
<img src="https://picsum.photos/200" class="animate-me">
<div class="spacer"></div>
您应该能够将其转化为您自己的用例,但如果您正在寻找其他东西,请分享更多细节。
关于屏幕上时的 Javascript 触发器(进度条),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59616960/