当滑块不在视野中时停止自动播放
最近,我开始自己编写所有代码,并且不使用jQuery,任何库或代码段。我想自己做以学习语言。不幸的是,我完全陷入困境。
我正在尝试让滑块在可见时自动播放,并在不可见时停止这种行为。
所以我写了一些代码来确定该部分是否在视图中,并提供了显示下一张幻灯片的功能,如下所示:
let windowWidth;
let windowHeight;
let scrollTop;
const panelTopics = document.getElementById("ihrStarkerPartner")
window.addEventListener("scroll", (e) => {
scrollTop = window.scrollY;
let panel = panelTopics;
let panelStart = panel.offsetTop;
let panelEnd = panel.offsetTop + panel.clientHeight;
let isInView;
if(scrollTop >= panelStart && scrollTop <= panelEnd ){
console.log("true");
isInView = true;
return true;
} else{
isInView = false;
showNextTopic(isInView);
console.log("false");
return false;
}
});
function showNextTopic(isInView){
if(isInView == true){
// Get index of current active topic
let currentActive = document.querySelector(".topic.is-active");
let currentIndex = parseInt(currentActive.dataset.number);
let nextIndex = currentIndex + 1;
setHeightOfTopicsContainer(getHeightOfActiveTopic(currentActive) + "px")
let refreshInterval = setInterval(function(){
currentActive.classList.remove("is-active");
topics.forEach( (topic, i) => {
if(topic.dataset.number == nextIndex){
// Add active class to icon
topic.classList.add("is-active");
setHeightOfTopicsContainer(getHeightOfActiveTopic(topic) + "px")
} else{
// Remove active class from icon
topic.classList.remove("is-active");
}
});
dots.forEach( (dot, i) => {
if(dot.dataset.number == nextIndex){
// Add active class to icon
dot.classList.add("is-active");
} else{
// Remove active class from icon
dot.classList.remove("is-active");
}
});
icons.forEach( (icon, i) => {
if(icon.dataset.number == nextIndex){
// Add active class to icon
icon.classList.add("is-active");
} else{
// Remove active class from icon
icon.classList.remove("is-active");
}
});
setBackgroundImage(nextIndex)
nextIndex++;
if(nextIndex > getTopicsCount() ){
nextIndex = 1;
}
}, 3000)
icons.forEach( icon => {
icon.addEventListener("click", () => {
clearInterval(refreshInterval)
});
});
}
}
这当然是行不通的,因为一旦查看了该部分,函数showNextTopic将遍历所有主题。不幸的是,我不知道如何构造代码来实现我想要的。如果有任何帮助/建议,我将不胜感激。