簡體   English   中英

為什么在使用 scrollTo 或 scrollIntoView 時不會觸發交叉點觀察者處理程序?

[英]Why intersection observer handler is not fired when using scrollTo or scrollIntoView?

在元素上設置了一個相交觀察器。 當元素滾動超過某個點時,交集觀察者處理程序將按預期觸發。 但是,如果單擊按鈕將元素滾動到同一點之后,則不會觸發處理程序。

這是為什么? 有沒有辦法在使用scrollTo / scrollIntoView時強制觸發處理程序?

 const container = document.getElementById("container"); const hello = document.getElementById("hello"); const button = document.getElementById("button"); const options = { rootMargin: "-100px 0px 0px 0px", threshold: 1 } const handleIntersect = entries => { entries.forEach((entry) => { console.log("handleIntersect") }); }; const observer = new IntersectionObserver(handleIntersect, options); observer.observe(hello); button.addEventListener("click", () => { container.scrollTo({ top: 120 }); })
 body { margin: 0; } #container { background-color: #ddd; height: 400px; overflow-y: auto; }.inner-container { height: 100px; border-bottom: 1px solid #bbb; position: absolute; top: 0; left: 0; right: 0; text-align: right; } #button { margin: 40px; font-size: 20px; } #hello { display: inline-block; padding: 20px 40px; background-color: blue; color: white; margin-top: 150px; margin-bottom: 500px; }
 <div id="container"> <div class="inner-container"> <button id="button">Scroll</button> </div> <div id="hello">Hello</div> </div>

你應該添加 isIntersecting 檢查

if(entry.isIntersecting){
console.log("hello")
}

我不知道這是否可以解決您的問題,但是我認為當我們將 scrollIntoView 鏈接到按鈕時,如果單擊該按鈕,我們會為滾動條的 position 指定一個值,例如當我們單擊具有 scrollTo 的按鈕時() function 我們希望滾動條位於特定位置,但這並不意味着滾動條滑動到與滾動鼠標時發生的動作相似的位置。

換句話說,交叉點 API 會在您越過特定 position 或某個點時觸發,但是即使您只是跳過該點並直接跳到所需的 Z4757FE07FD492A8BE0EA6A760D683D6E 時,它也不會觸發

如果您想知道,當您使用 scrollTo() 平滑滾動網頁時,您可以直觀地看到滾動條滑到特定點,就好像它通過了閾值點,但事實並非如此,在幕后滾動條只是跳過所有內容並直接移動指定的position。

解決問題的一種方法(效率不高)是使用循環,嘗試從當前頁面偏移值循環到目標值,而不是將值硬編碼到 scrollIntoView(),它確實為您提供了所需的 output 但滾動 animation 將貧窮,它失去了它的目標。

暫無
暫無

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

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