【问题标题】:How to implement Facebook like history.pushState system如何实现 Facebook 之类的 history.pushState 系统
【发布时间】:2016-12-31 20:42:18
【问题描述】:

我有 3 个相关问题要问

问题 1

在window.addEventListener('popstate', function(e) 上,我如何知道按下的按钮是forward() 还是back() 按钮。例如

window.addEventListener('popstate', function(e){
    var buttonDirection = // the button that was clicked
    if(buttonDirection == history.back()){
        // blah blah blah
    } else if(buttonDirection == history.forward()){
        // blah blah blah
    }
})

问题 2

我想在ajax 成功后pushState 以更改页面内容所以我这样做了,我真的不知道这是不是最好的方法

$.ajax({
    url: 'path.php',
    success: function(data){
        $('html').html(data);
        history.pushState('', '', 'path.php');
        var pushed = 'yes';
    }
})

现在问题出现在ajax 成功和pushed = yes 之后,然后我想在单击后退按钮以检索上一页内容时监听事件,因为在history.pushState 之后forward() 按钮是禁用,所以我这样做了

window.addEventListener('popstate', function(e){
    if(pushed == 'yes'){
        // run code to restore back previous page content
        $.ajax({
            url: 'current_page.php',
            success: function(data) {
                $('html').html(data);
                pushed = 'yesBack';
            }
        });
    }

    // now I want to run another code to replace the page content again if the forward button is clicked and pushed is == yesBack
    // that's where my reason for question 1 come out
    // so how do I know if the button that was clicked is the forward
})

最后一个问题

如果您在移动浏览器上研究 Facebook,您会发现:

  1. 如果您在个人资料图片相册页面上单击照片,则会触发 history.pushState 并使用 ajax 请求更改页面内容,现在将显示您单击的图像。
  2. 如果单击返回按钮,ajax 请求将再次用于检索上一页内容。
  3. 如果您再次单击前进按钮,则再次使用ajax 请求来更改页面内容以再次显示图像。
  4. 如果您现在通过单击下一个或上一个链接继续滚动图像,并且再次触发 history.pushState 并使用 ajax 请求检索新图像,无论您滚动了多少图像,如果您再次单击返回按钮,则会返回到第一页,即个人资料图片相册页面。
  5. 如果您随后再次单击前进按钮,则会将您带到您在单击后退按钮之前离开的页面。

现在我的第三个问题是如何在我自己的网页中实现所有这些观察。

我尝试查看 Facebook 源代码,但无法理解或找不到触发 history.pushState 的任何地方。请任何人回答我列出的任何问题或我可以阅读以获得答案的文档

【问题讨论】:

    标签: browser-history html5-history


    【解决方案1】:

    根据你的第一个问题,与question有关

    你必须自己实现它,这很容易。

    • 调用 pushState 时,为数据对象提供一个唯一递增的 id (uid)。
    • 当 onpopstate 处理程序被调用时;根据包含最后一个状态 uid 的持久变量检查状态 uid。
    • 使用当前状态 uid 更新持久变量。
    • 根据状态 uid 是大于还是小于上一个状态 uid 执行不同的操作。

    【讨论】:

    • 谢谢,那么如何在 window.popState 上获取页面的 url
    • 再次感谢,我已经从您的回答中找到了所有问题的解决方案:)
    猜你喜欢
    • 1970-01-01
    • 2011-10-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-09-10
    • 2010-12-21
    • 2019-05-10
    相关资源
    最近更新 更多