在返回导航时记住页面状态

Remember page state on navigation back

我有 3 个 DIV 会在点击时显示。在任何时候都只有一个 DIV 可见(其他 DIV 隐藏)。

问题是,#div1 有指向其他子页面的超链接。从这样的子页面返回后(通过点击浏览器的 "Back" 按钮) #div1 消失,滚动位置在它应该在的位置,但是 #div1 被隐藏了。如何让浏览器在从子页面返回后记住这个DIV状态和位置?

$(function () {
    $('#showdiv1').click(function () {
        $('div[id^=div]').hide();
        $('#div1').show();
    });
    $('#showdiv2').click(function () {
        $('div[id^=div]').hide();
        $('#div2').show();
    });
    $('#showdiv3').click(function () {
        $('div[id^=div]').hide();
        $('#div3').show();
    });
});

使用location.hash

一种方法是利用浏览器已经提供的功能:带有散列 hrefwindow.location.hash 和 CSS :target 选择器的锚点

有了这个HTML

<style>
    [id^="div"] {
        display: none;
    }
    [id^="div"]:target {
        display: block;
    }
</style>

<a href="#div1">div1</a>
<a href="#div2">div2</a>
<a href="#div3">div3</a>

<div id="div1">div1 <a href="//google.com">Google</a></div>
<div id="div2">div2 <a href="//whosebug.com">Stack Overflow</a></div>
<div id="div3">div3 <a href="//developer.mozilla.org">MDN</a></div>

如果 none 存在

,我们只需要一点 JavaScript 来设置默认哈希值
if(!location.hash) location.hash = "div1";

使用历史记录API - pushState

记住用户导航回您的页面时的状态 - 一个有用的方法是History API并从[=18=检索自定义数据] 对象。

鉴于此 HTML:

<style>
    .none {
        display: none;
    }
</style>

<button type="button" data-show="#div1">div1</button>
<button type="button" data-show="#div2">div2</button>
<button type="button" data-show="#div3">div3</button>

<div id="div1">div1 <a href="//google.com">Google</a></div>
<div id="div2">div2 <a href="//whosebug.com">Stack Overflow</a></div>
<div id="div3">div3 <a href="//developer.mozilla.org">MDN</a></div>

<script src="https://code.jquery.com/jquery-3.4.1.min.js"></script>

可以 pushState 要显示的元素的 ID 选择器history.pushState({sel: sel}, null); 并在页面加载时使用 history.state.sel[= 检索它24=]

jQuery( $ => {

    const $divs = $('[id^="div"]');
    const showElement = sel => {
        const $show = $(sel);
        $divs.not($show).addClass('none');
        $show.removeClass('none');
    }

    $('[data-show]').on('click', function () {
        const sel = $(this).data('show');
        history.pushState({sel}, null);
        showElement(sel);
    });

    showElement(history.state.sel || '#div1'); // Init. Fallback to "#div1"

});

使用存储 API - localStorage

或者,您可以将选择器字符串存储到 window.localStorage

(HTML 和 CSS 与前面的示例相同)

jQuery( $ => {

    const $divs = $('[id^="div"]');
    const showElement = sel => {
        const $show = $(sel);
        $divs.not($show).addClass('none');
        $show.removeClass('none');
    }

    $('[data-show]').on('click', function () {
        const sel = $(this).data('show');
        localStorage.sel = sel;
        showElement(sel);
    });

    showElement(localStorage.sel || '#div1'); // Init. Fallback to "#div1"

});