【发布时间】:2021-02-23 13:56:54
【问题描述】:
下面有这段代码,很简单:
- 用户滚动到某个部分,该部分被标记为 CSS 类“视图”
- 当我到达特定部分“someClsOfSection”时,我想触发使用 setInterval 向某个元素添加 20 个不同的类
- 每当我滚动时,条件都会满足,我不知道一旦进入此部分如何清除间隔... https://codepen.io/StevaNNN/pen/GRNOLyJ 这里是代码笔
const isFullySeen = el =>
el && typeof el.getBoundingClientRect === 'function'
&& el.getBoundingClientRect()['top'] +
window.scrollY + (window.innerHeight) <= window.innerHeight + window.scrollY;
$(document).ready(function () {
$(window).scroll(function () {
$('.section').each(function() {
if (isFullySeen(this) === true) {
$(this).addClass('in-view');
}
if(isFullySeen(this) && $(this).hasClass('.someClsOfSection')) {
let tempCls = 0;
let toTwentyPercent = setTimeout(function () {
setInterval(function () {
if (tempCls < 20) {
tempCls++;
$('.c100').addClass(`p${tempCls}`).animate();
}
}, 100);
}, 1000);
clearInterval(toTwentyPercent);
}
});
});
});
【问题讨论】:
-
我建议运行一次
isFullySeen(this)并将一个变量设置为其返回值。调用getBoundingClientRect()可能是一项昂贵的操作。此外,您在setTimeout中有一个setInterval,并且只捕获setTimeout的输出,这就是clearInterval不起作用的原因。
标签: javascript jquery scroll clearinterval