lum*_*mio 5 html javascript jquery
我正在创建一个单页并使用 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;
Run Code Online (Sandbox Code Playgroud)
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'));
});
});
Run Code Online (Sandbox Code Playgroud)
$(this).data('sjagpage') 包含 jQuery 元素。
当我不为滚动设置动画时,它只需要单击一次即可返回 - 但是当我现在为其设置动画时,它需要两次...为什么?
我认为问题在于,这event.preventDefault是一个由 jQuery 添加到对象的函数event,但您没有使用 jQuery 绑定事件处理程序。因此,默认导航不会被阻止,因此您最终会得到 2 个历史记录项目,可以通过它们向后导航。
代替:
window.onpopstate = scrollCurrentSection;
Run Code Online (Sandbox Code Playgroud)
你应该像这样绑定它:
$(window).bind("popstate", scrollCurrentSection);
Run Code Online (Sandbox Code Playgroud)