平滑滚动并使用 Firefox 上的 popState 返回按钮 - 需要单击两次
smooth scrolling and get back button with popState on Firefox - need to click twice
我正在尝试实现一个小代码,当我单击锚点时,我可以使用它获得平滑滚动(并且动画后会出现锚点名称),如果我按下浏览器的后退按钮并更新 URL(没有 #anchor 名称),我想返回页面顶部。
这是代码:
$(function() {
// Smooth scrolling when clicking on anchor
$('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;
$('html,body').animate({ scrollTop: target.offset().top - 55}, 300, function() {
location.hash = hash;
href = window.location.href;
history.pushState({page:href}, null, href);
});
return false;
}
}
});
// Get smooth scrolling to the top whith back button of browser
$(window).bind('popstate', function(event) {
var state = event.originalEvent.state;
var target = window.location.href.split('#');
var href = target[0];
if (state) {
$('html,body').animate({ scrollTop: 0 }, 300, function() {
window.location.href = href;
})
}
});
// First page loading
window.onload = function() {
history.replaceState({ path: window.location.href }, '');
}
});
上述所有功能在Safari和Chrome下都能很好地运行。但 Firefox 的情况并非如此:一旦执行平滑向下滚动,我需要在返回按钮上单击两次以重定向到页面顶部。
我已经在stackoverflow上看到了另一个问题,并尝试使用和不使用event.preventDefault,也只输入:
$('html').animate
或$('body').animate
但行为是一样的。
如果有人能看到为什么它不起作用。
谢谢
您正在触发此行中的其他历史记录更改location.hash = hash;
所以,我对你的代码做了一些更改,它现在可以在我的FF中工作。
在点击处理程序中,
$('html').animate({ scrollTop: target.offset().top - 55}, 300, function() {
href = window.location.href;
history.pushState({page:href}, null, href.split('#')[0]+hash);
});
此外,似乎$('html,body').animate
运行两次回调,因此弄乱了历史。这就是为什么我只留下html。
在popstate处理程序中,我删除了页面重新加载,但是如果您愿意,可以保留它:
if (state) {
$('html,body').animate({ scrollTop: 0 }, 300)
相关文章:
- button.单击两次删除附加操作后不工作
- 为什么jQuery下拉列表需要单击两次
- Rails-jQuery 为什么我必须单击两次才能显示 jQuery 效果
- 必须单击两次才能得到一个响应
- isHidden函数要求我在应用响应显示时单击两次
- 元素必须单击两次才能添加Class(自定义指令)
- 页面加载后的第一个锚定链接需要单击两次
- 单击两次后切换
- 必须在jQuery上单击两次
- 避免单击两次以开始编辑Backgrid中的布尔(复选框)单元格
- 单击两次提交按钮以发布表单
- 带有 OnClick 的 jQuery 链接标记 href 需要单击两次才能加载 AJAX
- Ionic:单击两次时显示活动/非活动按钮
- 事件仅在单击两次时激活
- jQuery 函数 - 单击两次返回一个值
- 必须单击两次才能触发
- 切换打开关闭必须在手机上单击两次
- 单击两次图标不会关闭下拉列表
- 平滑滚动并使用 Firefox 上的 popState 返回按钮 - 需要单击两次
- 在同一元素上单击两次,然后在另一个元素上单击两次,使第一个元素进入“单击”状态