jquery浏览内容和浏览器的后退按钮[重复]

问题描述 投票:0回答:1

这个问题在这里已有答案:

我是jquery的新手 - 当在导航菜单中单击按钮时,当前使用它来显示和隐藏网页上的内容(div)。我大致如下:

$(document).ready(function(){

   // show the "about" page
    $("#aboutButton").click(function(){
        $("#aboutPage").addClass("visible")
        $("#contactPage").removeClass("visible")
    });

   // show the "contact" page
    $("#contactButton").click(function(){
        $("#aboutPage").removeClass("visible")
        $("#contactPage").addClass("visible")
    });
});

虽然我很想知道如何更聪明地处理这个问题,但我最紧迫的问题是布鲁尔的后退按钮显然不能很好地解决这个问题。理想情况下,我希望它按预期工作:如果它被按下,我想回到我页面的最后一个可见部分/ div。我是多么怀疑我的做法一般都是非常错误的......

任何提示都会很优雅!谢谢

jquery css
1个回答
0
投票

您可以使用history.pushState“操纵”浏览器的历史记录。

浏览器显示的URL将更改,但不会加载新的URL。

然后你可以检测后退/前进按钮,为window.onpopstate分配一个事件处理程序(函数)

这只是一个例子:

$(document).ready(function(){

   // show the "about" page
    $("#aboutButton").click(function(){
        $("#aboutPage").addClass("visible")
        $("#contactPage").removeClass("visible")

        history.pushState( {page: "about"}, "", "about");
    });

   // show the "contact" page
    $("#contactButton").click(function(){
        $("#aboutPage").removeClass("visible")
        $("#contactPage").addClass("visible")

        history.pushState( {page: "contact"}, "", "contact");
    });

    // detect browser's back/forward buttons

    window.onpopstate = function( e ) {
        if( e.state.page === 'about' ) {
            $("#aboutPage").addClass("visible")
            $("#contactPage").removeClass("visible")
        }

        if( e.state.page === 'contact' ) {
            $("#aboutPage").removeClass("visible")
            $("#contactPage").addClass("visible")
        }       
    };
});

pushState接收访问者虚拟导航到的URL作为最后一个参数。第二个参数是(在写入时)未使用的。

第一个参数是您根据需要构建的对象,可以将信息存储在浏览器历史记录中。

onpopstate被触发(用户向后或向前导航)并且事件e被传递给回调时,您可以从e.state检索商店对象。

以上是容易的部分:现在变得更加烦人。

当您以编程方式操作URL时,用户可以将这些URL中的任何一个加入书签或重新加载页面,并且网站应该相应地做出响应。

该网站应该实际加载页面(而不是提出404)并且 - 取决于URL-显示#aboutPage#contactPage

供参考:Manipulating the browser history

© www.soinside.com 2019 - 2024. All rights reserved.