簡體   English   中英

將滾動類添加到數組的每個元素

[英]Adding class on scroll to each element of an array

大家好,我嘗試在使用 vanilla javascript 在視圖上顯示的元素添加一個類

<main>
        <section class="fs-sect" data-name="Banana"></section>
        <section class="fs-sect" data-name="Apple"></section>
        <section class="fs-sect" data-name="Avocado"></section>
        <section class="fs-sect" data-name="Orange"></section>
        <section class="fs-sect" data-name="Grapes"></section>
    </main>

這是我滾動到每個部分后的部分列表我想添加一個活動類並從任何其他部分中刪除這個類

<script>
const Myarray = document.querySelectorAll('.fs-sect');
// convert NodeList to array and map it
const Newarray = Array.from(Myarray).map((num,index) =>{
    const dataname = num.dataset.name;
    const myoffset = num.offsetTop;

    window.onscroll = function (e) {  
        let position_y = window.scrollY;
        if(position_y >= myoffset){
            document.querySelectorAll('.fs-sect').classList.remove('active-section');
            num.classList.add('active-section');
        } 
        console.log(position_y);
    } 
    return (
        //using index as ID and displaying data-attribute with offset position
        console.log(`I am a ${dataname} and my ID is ${index} and Im positioned at ${myoffset}`)
    );
});
</script>

我只設法循環到數組中獲取每個元素的索引 element.offset 但仍然需要在滾動后添加一個類,

謝謝您的幫助

if(position_y >= myoffset){
        document.querySelectorAll('.fs-sect').forEach(item => item.classList.remove('active-section'));
        num.classList.add('active-section');
    }.

試試這個,你會錯過 querySelectorAll 上的 forEach

工作示例。 注意:類更改僅在開發人員工具中可見。

 /* Prepare: */ function posY(elm) { var test = elm, top = 0; while (!!test && test.tagName.toLowerCase() !== "body") { top += test.offsetTop; test = test.offsetParent; } return top; } function viewPortHeight() { var de = document.documentElement; if (!!window.innerWidth) { return window.innerHeight; } else if (de && !isNaN(de.clientHeight)) { return de.clientHeight; } return 0; } function scrollY() { if (window.pageYOffset) { return window.pageYOffset; } return Math.max(document.documentElement.scrollTop, document.body.scrollTop); } function checkVisible(elm, eval) { eval = eval || "visible"; var vpH = viewPortHeight(), // Viewport Height st = scrollY(), // Scroll Top y = posY(elm), elementHeight = elm.offsetHeight; if (eval == "visible") return ((y < (vpH + st)) && (y > (st - elementHeight))); if (eval == "above") return ((y < (vpH + st))); } let sectionsVisible = ''; // Onscroll const onscroll = function(e) { let sections = document.querySelectorAll('.fs-sect'); let visibleSections = []; for (let section of sections) { const isVisible = checkVisible(section); section.classList.toggle('active-section', isVisible); if (isVisible) visibleSections.push(section.getAttribute('data-name')); } if (sectionsVisible != visibleSections.join(',')) { sectionsVisible = visibleSections.join(','); console.log('Visible:', sectionsVisible); } }; window.onscroll = onscroll; onscroll();
 section { height: 150px; background-color: #EEE; margin-bottom: 10px; position: relative; } section:after { display: block; position: absolute; right: 4px; top: 4px; content: attr(data-name); } section.active-section { background-color: #666; color: white; }
 <main> <section class="fs-sect" data-name="Banana"></section> <section class="fs-sect" data-name="Apple"></section> <section class="fs-sect" data-name="Avocado"></section> <section class="fs-sect" data-name="Orange"></section> <section class="fs-sect" data-name="Grapes"></section> </main>

暫無
暫無

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

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