簡體   English   中英

在頁面刷新和自動瀏覽器滾動時執行 function onscroll 事件的正確方法?

[英]Correct way to execute a function on onscroll event on page refresh and automatic browser scroll?

我有一個在 onscroll 事件上執行的 function,我注意到當我刷新頁面並且瀏覽器保留它的滾動時它不會執行 position。所以我想知道我是否需要顯式調用一次 function 或者有更好的方法來處理這個。 這是我的 function:`

function homeSliderAnimation(){
        if(document.body.classList.contains('home')){
            window.addEventListener('scroll', function(){
                let y = window.scrollY;
                let intersect = document.querySelector('.mainNavigation').getBoundingClientRect().bottom;
                let position = document.querySelector('.home--slider').scrollHeight - window.pageYOffset;
                y >= 100 ? document.body.classList.add('scrolled') : document.body.classList.remove('scrolled');
                position <= intersect ? document.body.classList.add('addBg') : document.body.classList.remove('addBg');
            });
        }
        
    }
    homeSliderAnimation();

`

嗯,我知道使這項工作的唯一方法是顯式調用 function 一次,然后在滾動事件上附加 function。

只需將事件回調 function 移動到單獨的 function 並將對第二個參數的引用傳遞給addEventListener function 並執行它。

function scrollEventHandler() {
    let y = window.scrollY;
    let intersect = document
        .querySelector(".mainNavigation")
        .getBoundingClientRect().bottom;
    let position =
        document.querySelector(".home--slider").scrollHeight -
        window.pageYOffset;
    y >= 100
        ? document.body.classList.add("scrolled")
        : document.body.classList.remove("scrolled");
    position <= intersect
        ? document.body.classList.add("addBg")
        : document.body.classList.remove("addBg");
}
function homeSliderAnimation() {
    if (document.body.classList.contains("home")) {
        window.addEventListener("scroll", scrollEventHandler);
        scrollEventHandler();
    }
}
homeSliderAnimation();

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM