簡體   English   中英

如何使用 vanilla javascript 判斷元素的頂部或底部何時滾動到頁面頂部

[英]How do I tell when the top or bottom of an element scrolls to the top of the page using vanilla javascript

我有一個 web 頁面,其中有兩個像這樣的 100% 高度 div...

<style>
        html, body{
            height: 100%;
            width: 100%;
            margin: 0;
            overflow: hidden;
        }
        #wrapper{
            height:100%;
            width:100%;
            overflow: auto;
        }
        .scroll-item{
            height: 100%;
            width: 100%;
        }
</style>
...
<body>
    <div id="wrapper">
        <div id="test1"
             class="scroll-item">Simple Test 1</div>
        <div id="test2"
             class="scroll-item">Simple Test 2</div>
    </div>
</body>

現在我想“選擇”當前滾動到的那個。 這意味着元素的頂部已經到達瀏覽器的頂部,但底部沒有。 這就是我感到困惑的地方,這里是 JS ......

<script type="module">
        const body = document.getElementsByTagName("body")[0];
        const handleScroll = function(info){
            const items = body.getElementsByClassName("scroll-item");
            for(let i = 0; i < length; i++){
                const item = items[i];
                // TODO How do I tell if it is there
            }
        }
        body.addEventListener("wheel",handleScroll);
</script>

我試過使用邊界框,但我不知道如何讓它正常工作。

我如何判斷元素的頂部或底部何時到達瀏覽器的頂部(給定導航欄的可能偏移量)?

您可以使用getBoundingClientRect() 它為您提供包含元素大小和坐標的DOMRect object。

 ... if (item.getBoundingClientRect().top < 0) { // items top has reached beyond window top } if (item.getBoundingClientRect().bottom > window.innerHeight) { // items bottom is beyond window bottom }...

有關高級用法,請參閱IntersectionObserver ,它檢測視口內的元素可見性。

使用包裝器獲取當前的 position 並監聽滾動事件,另外,最好監聽滾動而不是滾輪事件。

 // Use the wrapper to get and listen scroll const wrapper = document.querySelector('#wrapper') const handleScroll = function(event) { const top = wrapper.scrollTop; document.querySelectorAll('.scroll-item').forEach((item, index) => { // Calculate item bottom position const bottom = item.offsetTop + item.offsetHeight; // Is the scroll between item top and bottom? if(top >= item.offsetTop && top < bottom) { console.log(`Item ${index} is active`); } }); } // scroll event is more accurate than wheel wrapper.addEventListener("scroll", handleScroll);
 html, body{ height: 100%; width: 100%; margin: 0; overflow: hidden; } #wrapper{ height:100%; width:100%; overflow: auto; }.scroll-item{ height: 100%; width: 100%; }
 <body> <div id="wrapper"> <div id="test1" class="scroll-item">Simple Test 1</div> <div id="test2" class="scroll-item">Simple Test 2</div> </div> </body>

暫無
暫無

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

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