gpt4 book ai didi

javascript - 如何在页面加载时忽略 window.onpopstate?

转载 作者:IT王子 更新时间:2023-10-29 03:12:33 26 4
gpt4 key购买 nike

我正在玩 window.onpopstate,有件事让我有点恼火:

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

source

我测试过,是的,在 Chrome 和 Safari 5.1+ 中 popstate 事件在页面加载时触发,但在 Firefox 或 IE10 中没有。

问题是,我只想监听用户点击后退前进按钮的popstate事件(或者历史是通过 javascript 更改),但不想在页面加载时做任何事情。

换句话说,我想将 popstate 事件与 page load 事件与其他 popstate 事件区分开来。

这是我到目前为止尝试过的(我使用的是 jQuery):

$(function() {
console.log('document ready');

setTimeout(function() {
window.onpopstate = function(event) {
// Do something here
}, 10);
});

基本上,我尝试将我的 listener 函数绑定(bind)到 popstate 足够晚,以便在页面加载时不绑定(bind),只是稍后。

这似乎可行,但是,我不喜欢这个解决方案。我的意思是,我如何确定为 setTimeout 选择的 timeout 足够大,但又不会太大(因为我不想让它等待太多)。

我希望有更聪明的解决方案!

最佳答案

popstate 事件处理程序中检查 event.state 的 bool 真值:

window.addEventListener('popstate', function(event) {
if (event.state) {
alert('!');
}
}, false);

为确保这会起作用,始终在调用 history.pushState()history 时指定一个非null 状态参数.replaceState()。另外,考虑使用包装库,如 History.js跨浏览器提供一致的行为。

关于javascript - 如何在页面加载时忽略 window.onpopstate?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15896434/

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