【发布时间】:2016-01-27 15:15:11
【问题描述】:
我使用this link 中的以下代码来获得平滑的滚动页面和一个回调,一旦滚动完成,就会出现锚点的名称(我正在调用 .animate 的回调):
$(function() {
$('a[href*=#]:not([href=#])').click(function(event) {
event.preventDefault();
if (location.pathname.replace(/^\//,'') == this.pathname.replace(/^\//,'') && location.hostname == this.hostname) {
var target = $(this.hash);
target = target.length ? target : $('[name=' + this.hash.slice(1) +']');
if (target.length) {
var hash = this.hash; // 'this' will not be in scope in callback
$('html,body').animate({ scrollTop: target.offset().top - 55}, 300, function() {
location.hash = hash;
});
return false;
}
}
});
//Executed on page load with URL containing an anchor tag.
if($(location.href.split("#")[1])) {
var target = $('#'+location.href.split("#")[1]);
if (target.length) {
var hash = this.hash; // 'this' will not be in scope in callback
$('html,body').animate({ scrollTop: target.offset().top - 55}, 300, function() {
location.hash = hash;
});
return false;
}
}
});
我的问题是当我点击浏览器的后退按钮时,我不知道如何能够返回到页面顶部,即返回到以前的状态。例如,首先我在一个页面上(http://example.com/index.html),然后我点击一个锚点,我向下滚动到锚点,然后将锚点名称设置为 URL(http://example.com/index.htm#anchor)。但是如果我点击浏览器的后退按钮,我想被重定向到页面顶部。目前,使用上面的脚本,什么都没有发生。
更新
按照 Matthew Lymer 的回答,我通过添加进行了测试:
$(document).ready(function(event) {
var target = window.location.href.split("#")[1];
if (target.length) {
var hash = this.hash; // 'this' will not be in scope in callback
$('html,body').animate({ scrollTop: target.offset().top}, 300, function() {
location.hash = hash;
});
return false;
}
但是滚动到页面顶部的动画(当我按下返回按钮时需要)不起作用。
控制台打印:
Type Error: target is undefined
【问题讨论】:
-
按钮的 HTML 是什么?
-
这个按钮是我浏览器的后退按钮
-
看看
popstate这个函数,它在URL改变时执行。 Link
标签: javascript jquery scroll