HTML5的History API,如何知道用户点击了浏览器的前进/后退按钮?

7

我正在熟悉HTML5历史记录API,但我使用history.js来扩展兼容性。

我的问题是,我怎么知道:

            History.Adapter.bind(window,'statechange',function(){ // Note: We are using statechange instead of popstate
                var State = History.getState(); // Note: We are using History.getState() instead of event.state
                        /* Condition here to know if this change is a back or next button, and wich one?? */
            }); 

这是我的“完整”代码...
var the = this;
            var History = window.History;
            if ( !History.enabled ) {
                return false;
            }
            /* Store the initial content*/
            History.replaceState({
              content: $('#main').html()
            }, document.title, document.location.href);
            /* Bind to StateChange Event */
            History.Adapter.bind(window,'statechange',function(){ // Note: We are using statechange instead of popstate
                var State = History.getState(); // Note: We are using History.getState() instead of event.state
                //console.log(State);
                //History.log(State.data, State.title, State.url);
                console.log(history.length);
            });         
            /* triggers */
            $(document).on('click','a',function(e){
                e.preventDefault();
                var href = $(this).attr('href');
                var title = $(this).text();
                if(href == '#')
                    href = title;
                $.get('portfolio.html',function(data, response){
                    var html = $(data).find('#main-content').html();
                    //console.log(html);


                    $('#ajax-load').html(html);
                    History.pushState({ content: html}, title, href);
                    $('#ajax-load').css({ position:'absolute', 
                                          right: -$(window).width(), 
                                          top: the.header.height(), 
                                          width: $(window).width(),
                                          zIndex:999
                    }).animate({ right: 0 },300,function(){
                        console.log($('#main-content').length);
                        console.log($('#ajax-load').length);
                        $('#main-content').html(html);
                        $('#ajax-load').html('');
                    });

                });

            });

因为我需要检查历史记录的唯一原因就是为了下一个/返回按钮,对吗?否则锚点href规则。
-编辑-
基本上我需要从这里得到条件。
History.Adapter.bind(window,'statechange',function(){ 
                var State = History.getState(); 
                var condition = false;
                if(condition){
                    console.log('You clicked the next/back button');
                }
}); 

非常感谢您的提前帮助。


你有看过这个问题吗?https://dev59.com/p2w15IYBdhLWcg3w1_YN - Morgan Wilde
你能否告诉我如何判断使用History.js时状态的变化方向?或者参考这个链接:https://dev59.com/lHLYa4cB1Zd3GeqPThlb#16630032? - Adib Aroui
2个回答

2
您可以将所有状态(链接)记录在数组中,并在popstate(或statechange)事件发生时,将新位置与数组中的旧位置进行比较,以便知道用户是向前还是向后浏览历史记录。
或者您可以在pushState方法中传递一个时间戳到state obj参数中,并将其与旧时间戳进行比较。 选项1(存在问题,请勿使用)。
(function(){
    /*adding some init vars*/
    var the = this, arr = [], currPage;
    var History = window.History;
    if ( !History.enabled ) {
        return false;
    }
    /* Store the initial content*/
    History.replaceState({
      content: $('#main').html()
    }, document.title, document.location.href);
    /* add to arr*/
    arr[arr.length] = document.location.href;
    /*keep track of where we arein arr*/
    currPage = arr.length -1;
    /* Bind to StateChange Event */
    History.Adapter.bind(window,'statechange',function(){ // Note: We are using statechange instead of popstate
            var position, button;
            var State = History.getState(); // Note: We are using History.getState() instead of event.state
            //console.log(State);
            //History.log(State.data, State.title, State.url);
            console.log(history.length);
            position = arr.indexOf(document.location.href);
            button = position > currPage ? "fwd" : "back";
            currPage = position;
            console.log("You pressed The "+ button + " Button");
        });         
        /* triggers */
        $(document).on('click','a',function(e){
            e.preventDefault();
            var href = $(this).attr('href');
            var title = $(this).text();
            if(href == '#')
                href = title;
            $.get('portfolio.html',function(data, response){
                var html = $(data).find('#main-content').html();
                //console.log(html);


                $('#ajax-load').html(html);
                History.pushState({ content: html}, title, href);
                /* add to arr */
                arr[arr.length] = href;
                /* keep track */
                currPage = arr.length -1;
                $('#ajax-load').css({ position:'absolute', 
                                      right: -$(window).width(), 
                                      top: the.header.height(), 
                                      width: $(window).width(),
                                      zIndex:999
                }).animate({ right: 0 },300,function(){
                    console.log($('#main-content').length);
                    console.log($('#ajax-load').length);
                    $('#main-content').html(html);
                    $('#ajax-load').html('');
                });

            });

        });

}())

这个选项存在一个问题,如果相同的链接在历史记录中出现多次,它会变得混乱

选项2

    (function(){
    /*adding some init vars*/
    var the = this, currPageTime;
    var History = window.History;
    if ( !History.enabled ) {
        return false;
    }
    /* Store the initial content*/
    /* remember the current time */
    currPageTime = new Date().getTime();
    History.replaceState({
      content: $('#main').html(),
      time : currPageTime
    }, document.title, document.location.href);
    /* Bind to StateChange Event */
    History.Adapter.bind(window,'statechange',function(){ // Note: We are using statechange instead of popstate
            var pageTime, button;
            var State = History.getState(); // Note: We are using History.getState() instead of event.state
            //console.log(State);
            //History.log(State.data, State.title, State.url);
            console.log(history.length);
            /*NOTE: I never used getState so i dont know if State.time will exist, if not change it to whatever  holds the time we passed earlier */
            pageTime = State.time;
            button = pageTime > currPageTime ? "fwd" : "back";
            currPageTime =  pageTime;
            console.log("You pressed The "+ button + " Button");
        });         
        /* triggers */
        $(document).on('click','a',function(e){
            e.preventDefault();
            var href = $(this).attr('href');
            var title = $(this).text();
            if(href == '#')
                href = title;
            $.get('portfolio.html',function(data, response){
                var html = $(data).find('#main-content').html();
                //console.log(html);


                $('#ajax-load').html(html);
                /* keep track of time */
                currPageTime = new Date().getTime();
                History.pushState({ content: html, time: currPageTime}, title, href);
                $('#ajax-load').css({ position:'absolute', 
                                      right: -$(window).width(), 
                                      top: the.header.height(), 
                                      width: $(window).width(),
                                      zIndex:999
                }).animate({ right: 0 },300,function(){
                    console.log($('#main-content').length);
                    console.log($('#ajax-load').length);
                    $('#main-content').html(html);
                    $('#ajax-load').html('');
                });

            });

        });

}())

PS:我还没有测试它是否有效,如果无法正常工作,请创建一个fiddle并尝试修复它


1
您不需要特别查看下一个或后退按钮是否被触发。 当按下下一个或后退按钮时,将触发“statechange”事件。因此,根据URL更改,您可以操作您的HTML内容。
另外,“statechange”在不同的浏览器中也会在不同的场合触发。 例如,Chrome会在任何页面加载时立即加载“statechange”事件,即使是刷新,而这在Firefox中并非如此。

我确实想知道,因为我想在这些情况下以不同的方式处理响应... ;) - Toni Michel Caubet

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接