【问题标题】:How to use browser back button to go back to the previous section I was in one-page application?如何使用浏览器返回按钮返回上一节我在单页应用程序中?
【发布时间】:2022-06-23 19:38:13
【问题描述】:

在一个页面的网络应用程序中,有一个很大的问题要导航到我在应用程序中使用浏览器的后退按钮的上一部分。用 JavaScript 怎么做?

【问题讨论】:

    标签: javascript html css frontend visual-web-developer


    【解决方案1】:

    如果您正在创建一个单页网络应用程序,其中您的 html 正文有不同的部分,并且您希望通过后退按钮导航到您所在的上一个部分。这个答案会对你有所帮助。

    您的网站部分以# 区分。如:

    your-web-address.com/#section-name

    只需几步:

    在您的 html 正文的每个部分中添加一个类和一个 id。这里是“.section”

    <section class="section" id="section-name">...</section>
    

    在链接的 css(例如 style.css)文件中添加两个 CSS 类到您的 html(例如 index.html)文件,例如:

    .section .hide {
      display: none;
    }
    .section .active{
     dislplay: block;
    }
    

    在您链接的 .js(例如 main.js)文件中添加此 JavaScript 函数到您的 html 文件。

    window.onpopstate = function () {
        if (location.hash !== "") {
            const hash = location.hash;
            // Deactivating existing active 'section'
            document.querySelector(".section.active").classList.add("hide");
            document.querySelector(".section.active").classList.remove("active");
            // Activating new 'section'
            document.querySelector(hash).classList.add("active");
            document.querySelector(hash).classList.remove("hide");
        }
    }
    

    【讨论】:

      猜你喜欢
      • 2020-09-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-07-25
      • 1970-01-01
      • 2011-10-31
      • 1970-01-01
      • 2011-07-11
      相关资源
      最近更新 更多