任何人都可以建议吗?我正在编写一个脚本,当一个人将屏幕滚动到某个块时,它会启动一个计时器。计时器倒计时 10 秒。如果在技术方面。这一次一个人滚动了这个块(无论向哪个方向),然后计数器被重置,如果他研究了这个块10秒,那么另一个块出现了。所以,实际上,一个问题。我最初是否从右侧开始处理问题,为什么退出块时 clearInterval 不起作用?
// function printNumbers(from, to) {
// let current = from;
// const timerBox = document.querySelector('.timer');
// let timerId = setInterval(function() {
// timerBox.innerHTML = current;
// if (current == to) {
// clearInterval(timerId);
//
// }
// current++;
// }, 1000);
// }
document.addEventListener("DOMContentLoaded", function() {
let counter = 0;
let currentNum = 0;
const timerBox = document.querySelector('.timer');
const element = document.querySelector('.screen3');
const elemHid = document.querySelector('.screen-hidden');
window.addEventListener('scroll', function(){
const elemPosition = {
top: window.pageYOffset + element.getBoundingClientRect().top,
bottom: window.pageYOffset + element.getBoundingClientRect().bottom
}
const windowPosition = {
top: window.pageYOffset,
bottom: window.pageYOffset + document.documentElement.clientHeight
}
if( elemPosition.top < windowPosition.bottom && elemPosition.bottom > windowPosition.top && counter == 0 ){
let timerId = setInterval(function(){
timerBox.innerHTML = currentNum;
if(currentNum == 10){
clearInterval(timerId);
}
currentNum++;
}, 1000);
counter = 1;
}
else {
clearInterval(timerId);
}
});
});
.section{ height: 700px; }
.screen-hidden{display: none;}
.timer{ position: fixed; top: 0; left: 0; display: inline-block; padding: 20px; background: black; color: white; }
<div class="timer">0</div>
<section class="section screen1" style="background-color: red;"></section>
<section class="section screen2" style="background-color: yellow;"></section>
<section class="section screen3" style="background-color: green;"></section>
<section class="section screen-hidden" style="background-color: black;"></section>
<section class="section screen4" style="background-color: blue;"></section>
<section class="section screen5" style="background-color: pink;"></section>
如果突然有人需要