我想知道如何在滚动时更新URL中的哈希值。
我使用以下代码更新单页设计中的当前状态。
function setActiveListElements(){
// Get the offset of the window from the top of page
var windowPos = $(window).scrollTop();
$('#primary-navwrapper').find('li a[href^="#"]').each(function () {
var anchorId = $(this);
var target = $(anchorId.attr("href"));
//console.log(target);
var offsetTop = target.position().top - offset;
//var offsetBottom = offsetTop + target.height();
//var top = sidebar.offset().top;
if (target.length > 0) {
//console.log(target.position().top + target.height());
//if(windowPos >= offsetTop && windowPos <= offsetBottom) {
if (target.position().top - offset <= windowPos && target.position().top + target.height() + offset > windowPos) {
$('#primary-navwrapper li a').removeClass("current");
anchorId.addClass("current");
}
}
});
}
滚动时调用此函数。 现在我提出了以下解决方案:
function setActiveListElements(){
// Get the offset of the window from the top of page
var windowPos = $(window).scrollTop();
$('#primary-navwrapper').find('li a[href^="#"]').each(function () {
var anchorId = $(this);
var target = $(anchorId.attr("href"));
//console.log(target);
var offsetTop = target.position().top - offset;
//var offsetBottom = offsetTop + target.height();
//var top = sidebar.offset().top;
if (target.length > 0) {
//console.log(target.position().top + target.height());
//if(windowPos >= offsetTop && windowPos <= offsetBottom) {
if (target.position().top - offset <= windowPos && target.position().top + target.height() + offset > windowPos) {
$('#primary-navwrapper li a').removeClass("current");
anchorId.addClass("current");
window.location.hash = $(this).attr('href');
}
}
});
}
但是当我滚动时你会看到哈希完全翻转并冻结。这可能是什么?
答案 0 :(得分:0)
使用历史记录API:
history.pushState(null, null, '#myhash');
处理那些不支持此事的人:
if (history.pushState) {
history.pushState(null, null, '#myhash');
} else {
location.hash = '#myhash';
}