gpt4 book ai didi

javascript - popstate - 需要在后退按钮上点击两次才能真正返回

转载 作者:搜寻专家 更新时间:2023-10-31 21:51:43 27 4
gpt4 key购买 nike

我正在创建一个单页并使用 pushState 来更改地址。现在,如果我向后推,popstate 将被触发,我想为页面从当前位置滚动到最后一个位置设置动画。这当然有效,但页面会跳到顶部。

有谁知道如何防止这种行为?我正在使用 jQuery 来设置滚动动画....

谢谢:)

//编辑: 好的,我发现,如果我设置滚动动画然后更改 url,它不会跳转 - 但现在我必须双击后退按钮才能获得返回...
http://www.testwebseiten.at/user/falk/stein-jagersbacher.at

代码有点乱,稍微解释一下:

    var scrollCurrentSection = function(event) {
if (typeof event.preventDefault != 'undefined')
event.preventDefault();

var page = "";
if (window.location.href.substr(-1) == '/')
page = sjag.index;
else
page = window.location.href.match(/([^\/]+)$/)[1];

$this = $('a[href$="'+page+'"]');
if ($this.length) {
sjag.scrollToSection($this);
}
}
window.onpopstate = scrollCurrentSection;

sjag 包含多个选项和方法...因此 sjag.index 仅包含“index.php”,sjag.scrollToSection 包含动画。

单击导航链接时,将调用以下函数:

    // set navi
$("#navi a, #navi-add a").click(function(event) {
var data = $(this).data('sjagpage');
if (typeof data == 'undefined')
return;

event.preventDefault();
// animate scrolling
$this = $(this);
sjag.scrollToSection($(this), function() {
history.pushState("", "", $this.attr('href'));
});
});

$(this).data('sjagpage') 包含 jQuery 元素。

当我不为滚动设置动画时,只需单击一下即可返回 - 但当我现在为其设置动画时,它需要两次...为什么?

最佳答案

我认为问题在于 event.preventDefault 是由 jQuery 添加到 event 对象的函数,但您没有使用 jQuery 绑定(bind)事件处理程序。因此,不会阻止默认导航,因此您最终会得到 2 个历史记录项,通过它们可以返回。

代替:

window.onpopstate = scrollCurrentSection;

你应该像这样绑定(bind)它:

$(window).bind("popstate", scrollCurrentSection);

关于javascript - popstate - 需要在后退按钮上点击两次才能真正返回,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9634518/

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