在具有固定顶部菜单和锚点导航的一页布局上,我有一个“scrollspy”,它可以更改滚动时的片段标识符,根据滚动位置为菜单链接提供一个活动类,并使用 Velocity.js 将滚动动画到锚点。
不幸的是,它还做了什么,当单击浏览器后退按钮时,它会带我完成滚动方式的所有步骤,这意味着我加载网站并向下和向上滚动一点,然后频繁地点击后退按钮,浏览器也会向下滚动及以上,但实际上不会转到上次访问的 ID 或返回浏览器历史记录。
这是jsfiddle。 https://jsfiddle.net/tgf20e9k/
// jQuery on DOM ready
// In-Page Scroll Animation with VelocityJS
// ------------------------------------------------ //
// https://john-dugan.com/fixed-headers-with-hash-links/
$('.menu-a').on('click', function(e) {
var hash = this.hash,
$hash = $(hash)
addHash = function() {
window.location.hash = hash;
};
$hash.velocity("scroll", { duration: 700, easing: [ .4, .21, .35, 1 ], complete: addHash });
e.preventDefault();
});
// ScrollSpy for Menu items and Fragment Identifier
// ------------------------------------------------ //
// https://jsfiddle.net/mekwall/up4nu/
$menuLink = $('.menu-a')
var lastId,
// Anchors corresponding to menu items
scrollItems = $menuLink.map(function(){
var item = $($(this).attr("href"));
if (item.length) { return item; }
});
$(window).scroll(function(){
// Get container scroll position
var fromTop = $(this).scrollTop()+ 30; // or the value for the #navigation height
// Get id of current scroll item
var cur = scrollItems.map(function(){
if ($(this).offset().top < fromTop)
return this;
});
// Get the id of the current element
cur = cur[cur.length-1];
var id = cur && cur.length ? cur[0].id : "";
if (lastId !== id) {
lastId = id;
// Set/remove active class
$menuLink
.parent().removeClass("active")
.end().filter("[href='#"+id+"']").parent().addClass("active");
}
// If supported by the browser we can also update the URL
// http://codepen.io/grayghostvisuals/pen/EtdwL
if (window.history && window.history.pushState) {
history.pushState("", document.title,'#'+id);
}
});
使用上面的代码,以下工作正常:
Question
Part 1:当您在小提琴上滚动一点,然后点击后退按钮时,您会看到滚动条以完全相同的方式“移动”,记住已完成的滚动。
我需要后退按钮像平常一样工作。
a) 返回浏览器历史记录并返回您所在的页面/网站,然后
b) 当点击锚链接 (i),然后点击锚链接 (ii),然后点击后退按钮时,页面应返回到锚链接 (i)。
Part 2: Since history.pushState
IE8不支持我正在寻找一种使用方法window.location.hash = $(this).attr('id');
反而。无论我在代码末尾尝试什么,我都无法得到window.location.hash = $(this).attr('id');
上班。我真的不想使用 HistoryJS 或其他东西来实现此目的,但有兴趣学习并自己编写它。
除了后退按钮损坏的行为之外,我想要的所有其他行为都已经存在,现在我只需要修复后退按钮的行为。
edit我想我可能找到了解决方案here https://stackoverflow.com/a/1489802/1010918,如果我能做到这一点,将进行测试,然后详细回复。
Related:
在 Firefox 上使用 popState 平滑滚动和返回按钮 - 需要单击两次 https://stackoverflow.com/questions/35086895/smooth-scrolling-and-get-back-button-with-popstate-on-firefox-need-to-click-tw
jQuery 在页面后退按钮滚动 https://stackoverflow.com/questions/16527543/jquery-in-page-back-button-scrolling
修改document.location.hash而不滚动页面 https://stackoverflow.com/a/1489802/1010918
如何检测浏览器后退按钮事件 - 跨浏览器 https://stackoverflow.com/a/25806609/1010918