我正在创建一个页面,并使用pushState更改地址。现在,如果我向后推,popstate就会被触发,我想让页面从当前位置滚动到最后一个位置。这当然有效,但页面会跳到顶部。
有人知道如何防止这种行为吗?我正在使用jQuery来动画滚动。。。。
谢谢:)
//edit:好吧,我发现了,如果我设置滚动动画,然后更改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绑定事件处理程序。因此,默认导航不会被阻止,因此您最终会有两个历史项目要导航回来。
代替:
window.onpopstate = scrollCurrentSection;
你应该把它绑定成这样:
$(window).bind("popstate", scrollCurrentSection);