簡體   English   中英

如何將溢出的 div 滾動到某個主題標簽(錨點)?

[英]How do I scroll an overflowed div to a certain hashtag (anchor)?

在我的網頁上,我有一個溢出的 div(即帶有垂直滾動條)。 在 div 中,我有帶有 id 的錨點。 當我將這些 id 之一放在 URL (mypage.html#id) 中時,我希望 div 而不是頁面滾動到該錨點。

我該怎么做,最好使用純 JavaScript? 如果它太復雜,我會使用 jQuery,但我不會在這個項目中將它用於其他任何事情。

$('.overflow').scrollTop($('#anchor').offset().top);

您完全沒有理由不能將其轉換為標准的 javascript。

請注意,如果錨元素上有邊距,滾動將關閉。

您是否嘗試在錨點上設置focus()

任何帶有 tabindex 的 DOM 元素都是可聚焦的,任何具有焦點的元素都會被瀏覽器滾動到視圖中。

這是一個純 Javascript (ECMA 6) 解決方案,類似於 Ariel 的答案。

const overflow = document.querySelector('.overflow');
const anchor = document.getElementById('anchor');

// Get the bounding client rectangles for both
// the overflow container and the target anchor
const rectOverflow = overflow.getBoundingClientRect();
const rectAnchor = anchor.getBoundingClientRect();

// Set the scroll position of the overflow container
overflow.scrollTop = rectAnchor.top - rectOverflow.top;

對於 2021 年幾乎所有主要瀏覽器中的那些人,請使用element.scrollIntoView()

https://developer.mozilla.org/docs/Web/API/Element/scrollIntoView

Element 接口的 scrollIntoView() 方法滾動元素的父容器,以便調用 scrollIntoView() 的元素對用戶可見 - MDN Web Docs

例子:

var myEl = document.getElementById("child");
myEl.scrollIntoView()

或帶參數-- Safari 或 Internet Explorer 不支持:

myEl.scrollIntoView({
    block: "center" // Start, center, end, or nearest. Defaults to start.
    behavior: "smooth"
})

暫無
暫無

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

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