我使用 Bootstrap 的滚动 spy 来更改页面滚动上突出显示的导航栏项目,然后使用 history.replaceState
将哈希添加到网址。 This question给了我那部分的想法。我还使用一些 jquery 在单击导航项时实现“平滑滚动”,并在“平滑滚动”向下到 anchor 时关闭滚动 spy ,然后将哈希添加到 url 并重新打开滚动 spy 。
scrollspy 部分工作正常,但单击导航链接时出现问题。它在 Chrome 和 Firefox 中按预期工作,但在 IE 10 和 11 中,当单击链接时,它会在 url 中的哈希值之前添加 undefined
,我不知道为什么。
这是我的脚本:
//initiate scroll spy
$('body').scrollspy({ target: '.spy-active', offset: $offset + 1 });
$('.spy-active').on('activate.bs.scrollspy', function (e) {
if (history.replaceState) {
history.replaceState(null, "", $('a[href*=#]:not([href=#])', e.target).attr("href"));
}
});
//smooth scroll
$('a[href*=#]:not([href=#])').click(function (e) {
e.preventDefault();
//deactivate scrollspy for duration of transition
$('nav').removeClass('spy-active');
//remove active class from all list items
$('li').each(function () {
$(this).removeClass('active');
});
//add active class to clicked item
$(this).parent().addClass('active');
var target = this.hash;
var $target = $(target);
$('html, body').stop().animate({
'scrollTop': $target.offset().top - $offset
}, 500, 'swing', function () {
if (history.replaceState) {
history.replaceState(null, "", target);
}
//reactivate scrollspy
$('nav').addClass('spy-active');
});
});
我的网站是here
最佳答案
当您单击导航链接时,此行会在 IE 中执行:
history.replaceState(null, "", $('a[href*=#]:not([href=#])', e.target).attr("href"));
如果在 e.target
中找不到链接,则 .attr("href")
的结果为 undefined
。因此,您需要检查是否找到链接,然后调用 history.replaceState
:
var matchLink = $('a[href*=#]:not([href=#])', e.target);
if(matchLink.length) {
history.replaceState(null, "", matchLink.attr("href"));
}
关于javascript - History.replaceState 未定义 IE11,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25040842/