gpt4 book ai didi

javascript - 有没有办法延迟 popstate 事件?

转载 作者:行者123 更新时间:2023-11-28 00:25:24 32 4
gpt4 key购买 nike

我尝试了几种方法,看看是否可以创建一个跨浏览器解决方案来延迟 popstate 事件,但没有任何运气。

大家有什么想法或想法吗?

下面显然不起作用,但有些效果:

$(window).on('popstate', function(e) {

// something here to delay the history pageload

console.log('a wild console has appeared!');

});

因此流程将遵循以下顺序:

  • 点击了浏览器“后退”或“前进”按钮
  • 运行初始代码
  • 页面更改之前的延迟
  • 页面更改

最佳答案

根据Documentation popstate 事件是

only triggered by doing a browser action such as a click on the back button

所以我不相信当用户点击“前进”时它会被触发(并且在某些浏览器中有所不同)

全文如下,供引用:

The popstate event is fired when the active history entry changes. If the history entry being activated was created by a call to history.pushState() or was affected by a call to history.replaceState(), the popstate event's state property contains a copy of the history entry's state object.

Note that just calling history.pushState() or history.replaceState() won't trigger a popstate event. The popstate event is only triggered by doing a browser action such as a click on the back button (or calling history.back() in JavaScript).

Browsers tend to handle the popstate event differently on page load. Chrome (prior to v34) and Safari always emit a popstate event on page load, but Firefox doesn't.

上面更新了答案

您的代码有效。 (见下文) - 我添加了一个元素来触发事件(您可以在控制台中看到结果)

在使用之前,请确保在 HTML 中包含 jQuery 库。

$(window).on('popstate', function(e) {
console.log('fired instantly!');
var timer = setTimeout(function() {
console.log('delayed popstate!');
clearTimeout(timer);
}, 1000);
});

$(window).trigger( 'popstate') ;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

关于javascript - 有没有办法延迟 popstate 事件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29568783/

32 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com