我目前正在為我的網站使用 Bootstrap。
我使用的是 Bootstrap 的導航欄,我的每個 HTML 部分標簽都有一個 ID(例如:#about-section、#contact-section)
這允許我使用錨標簽href="#about-section"來平滑滾動到任何部分。
這非常有效,但是一旦我將導航欄引入靜態,每當我單擊應該平滑滾動到該部分的導航鏈接時,它會平滑滾動,但導航欄覆寫了該部分的大部分。
我見過解決方案,但使用 jQuery。執行此操作的本機 JS 方法是什么?
uj5u.com熱心網友回復:
我可以告訴你兩種方法來解決這個問題。方法 1 使用 CSS 很容易,方法 2 使用 javascript。
方式一:padding-top
用于padding-top您的部分。的值padding-top將是導航欄的高度。所以當滾動到那個部分時,實際上它會從頂部開始。但是對于 padding-top 你可以看到導航欄后面的部分。
方式 2:Javascript
const links = document.querySelectorAll(".nav-link"); // or any other selector what you want
for (const link of links) {
link.addEventListener("click", scrollToSection);
}
function scrollToSection(e) {
e.preventDefault();
const href = this.getAttribute("href");
const offsetTop = document.querySelector(href).offsetTop;
const navbarHeight = document.querySelector(".navbar").offsetHeight
scroll({
top: offsetTop - navbarHeight,
behavior: "smooth"
});
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/534544.html
