【问题标题】:popstate fire on page load页面加载时弹出状态触发
【发布时间】:2014-06-09 21:37:36
【问题描述】:
$(window).on('popstate', function(){
    window.history.go(-1);
});

当用户单击返回按钮时,我有一个页面使用 popstate

但在某些浏览器中,popstate 会在页面加载时触发,而不是单击返回按钮。

它发生在 Safari 和触摸设备中。

【问题讨论】:

标签: javascript jquery


【解决方案1】:

最简单的破解/解决方案是在初始页面加载后立即在 setTimeout 中添加 popstate 侦听器。

 setTimeout( function() {
    window.addEventListener( 'popstate', myPopStateHandler, false );
  }, 500 );

我厌倦了将 setTimeout 用于解决方案,这似乎总是一团糟。但是现在,嘿,它有效。

【讨论】:

    【解决方案2】:

    添加一个标志来检测页面加载为我解决了这个问题。

    编辑:添加 Safari 浏览器检测,否则在 Firefox 或 Chrome 中首次单击后退按钮不会触发 popstate 事件。

    var isSafari = /^((?!chrome).)*safari/i.test(navigator.userAgent),
        firstLoad = true;
    $(window).on('popstate', function(){
        if (isSafari && firstLoad) {
            firstLoad = false;
            return;
        } else {
            // run your popstate code
        }
    });
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-04-11
      • 2021-08-04
      • 1970-01-01
      • 2021-07-20
      • 2021-10-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多