history.pushState打破浏览器后退按钮

时间:2012-11-05 21:35:58

标签: jquery ajax browser-history pushstate

我正在开发一个单页应用程序,其中每个部分都是通过ajax加载的。主页是它自己的页面,然后单击“关于”,它会将您带到单页面应用程序。我已经获得了更改每个部分的网址以及浏览器上的后退和前进按钮以使用此代码段:

$('.down-button').on('click', function() {
        var stateObj = { principles: "about-principles" };
        history.pushState(stateObj, null, "about-principles");
        $('#principles-wrap').scrollintoview({ duration: 1000 });
    });

但是,当您一直点击返回主页时,主页不会刷新,您将保持在“关于”页面上。或者,如果单击返回主页的链接,则会出现404错误。

我错过了什么?

修改

以下是代码的其余部分:

function button_scroll () {
// Call scrollIntoView js file into this 
$.getScript("/js/jquery.scrollintoview.min.js", function() {
    $('.down-button').on('click', function() {
        var stateObj = { principles: "about-principles" };
        history.pushState(stateObj, null, "about-principles");
        $('#principles-wrap').scrollintoview({ duration: 1000 });
    });
    $('.up-button-principles').on('click', function() {
        var stateObj = { mission: "about-mission" };
        history.pushState(stateObj, null, "about-mission");
        $('#mission-wrap').scrollintoview({ duration: 1000 });
    });
    $('.down-button-principles').on('click', function() {
        var stateObj = { snapshot: "about-snapshot" };
        history.pushState(stateObj, null, "about-snapshot");
        $('#snapshot-wrap').scrollintoview({ duration: 1000 });
    });
    $('.up-button-snapshot').on('click', function() {
        var stateObj = { principles: "about-principles" };
        history.pushState(stateObj, null, "about-principles");
        $('#principles-wrap').scrollintoview({ duration: 1000 });
    });
    $('.down-button-snapshot').on('click', function() {
        var stateObj = { people: "about-people" };
        history.pushState(stateObj, null, "about-people");
        $('#people-wrap').scrollintoview({ duration: 1000 });
    });
    $('.up-button-people').on('click', function() {
        var stateObj = { snapshot: "about-snapshot" };
        history.pushState(stateObj, null, "about-snapshot");
        $('#snapshot-wrap').scrollintoview({ duration: 1000 });
    });

});

}

//Dropdown
$(document).ready(function () {
$(window).on('load resize', function () {
    resize_mission();
    resize_principles();
    resize_snapshot();
    resize_people();
    button_scroll();
});
var dropDown = $('.dropdown');
$('h3.about').on('click', function() {
    dropDown.slideDown('fast', function() {
        var url = 'about2.php'
        var stateObj = { mission: "about-mission" };
        history.pushState(stateObj, null, "about-mission");
        $.get(url, function(data) {
            resize_mission();
            resize_principles();
            resize_snapshot();
            resize_people();
            button_scroll();
        });
    });
});

});

这就是我正在做的一切。没有插件。

1 个答案:

答案 0 :(得分:2)

您是否在关于页面的主页上停止点击事件的默认操作?就像您在链接上使用preventDefault()stopPropagation()一样,点击您的关于此页面的内容?您是否也停止了hashchange事件的默认行为?我们可能需要在您的历史实现中看到更多代码。你在使用任何历史插件吗?