簡體   English   中英

JS 在 window.scroll 后滾動回頂部

[英]JS scrolling back to top after window.scroll

嗨,當我訪問我的網頁並且 # 出現在 url 中時,我需要它去那個部分。 所以我所做的是添加一個JS腳本

document.addEventListener('DOMContentLoaded', () => {
    // setupScrolling();
    setupTitle();
    if (window.location.hash) {
        const element = document.getElementById(window.location.hash);
        if (element) {
            const offset = element.offsetTop;
            const a = offset - (document.querySelector('header')?.offsetHeight);
            window.scroll({
                top: offset,
                behavior: 'smooth'
            });
            return false;
        }
    }
});

這是我添加到 public/index.html 中的腳本

但是,行為不正確.. 一旦頁面向下滾動到該部分,它將自動返回到站點的頂部,我不知道為什么。

誰能幫助我並告訴我應該怎么做?

你真的不需要javascript來做到這一點。 您只能使用 HTML。
只需向您希望允許用戶跳轉到的元素添加一個 id。
然后,當某個元素的 id 以哈希形式存在於您的網頁 URL 中時,頁面將在加載頁面時直接滾動到該元素。

例如,假設我有一個 id 為“down-section”的元素

<span id="down-section">Down Section in the page</span>

訪問鏈接https://your-domaine.com#down-section會直接跳轉到“頁面中的Down Section ”。

添加平滑行為。

在這種特殊情況下,您可能希望添加平滑行為。 只需將這樣的代碼添加到您的 javascript 腳本中:

if (!!document.location.hash){
    document.getElementsByTagName('html')[0].style.scrollBehavior = 'smooth';
}

暫無
暫無

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

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