我在使用平滑滚动功能时遇到了一些麻烦。锚点中有特殊字符(åäö),但是在获取$(this.hash)
时会对其进行编码,因此给了我Syntax error, unrecognized expression: #sp%C3%A5r1
(锚点链接到#spår1)。
如何防止编码使它们链接到正确的ID?我尝试对URI进行解码,但无济于事,因为jQuery在(var target = $(this.hash)
)之前的语句中抛出了错误
这是代码:
$('a[href*=\\#]:not([href=\\#])').click(function() {
if (location.pathname.replace(/^\//, '') == this.pathname.replace(/^\//, '') ||
location.hostname == this.hostname) {
var navHeight = 0;
if (document.querySelector('#nav')) {
navHeight = document.querySelector('#nav').offsetHeight;
}
//GET HASH FROM ANCHOR
var target = $(this.hash);
target = decodeURI(target);
target = target.length ? target : $('[name=' + this.hash.slice(1) + ']');
if (target.length) {
$('html,body').animate({
scrollTop: target.offset().top - navHeight
}, 100);
return false;
}
}
});