// Load jQuery.js firstly
jQuery
(
function
()
{
jQuery
(
'a[href*=#]'
).
click
(
function
()
{
if
(
location
.
pathname
.
replace
(
/^\//
,
''
)
==
this
.
pathname
.
replace
(
/^\//
,
''
)
&&
location
.
hostname
==
this
.
hostname
)
{
var
$target
=
jQuery
(
this
.
hash
);
var
$url
=
this
.
hash
.
slice
(
1
);
var
$scrollTime
=
500
;
function
updateUrl
()
{
window
.
location
.
hash
=
encodeURIComponent
(
$url
);
}
$target
=
$target
.
length
&&
$target
||
jQuery
(
'[name='
+
$url
+
']'
);
if
(
!
$url
)
{
return
false
;
}
else
if
(
$target
.
length
)
{
var
targetOffset
=
$target
.
offset
().
top
;
jQuery
(
'html,body'
).
animate
({
scrollTop
:
targetOffset
},
$scrollTime
);
setTimeout
(
updateUrl
,
$scrollTime
+
100
)
return
false
;
}
}
});
});
情形1:
目标页面有个 `position:fixed;height:50px;` 的顶部导航栏,这部分会遮住文章正文内容,正文中的所有`#part-1` 这样的锚点都会有50px的误差,解法很简单,如下:
jQuery('html,body').animate({
scrollTop: targetOffset - 50
}, $scrollTime);
如果要兼容从别的页面锚过来,可以再加个触发器监控`location.hash`:
$('body').append('<a id="anchor-temp" href="' + location.hash + '"></a>');
window.setTimeout(function() {
$('#anchor-temp').trigger('click');
}, 2000);
情形2:
需要强行根据URL中的锚标记进行页面跳转,如:
http://aaa.bbb/ccc#part-1 -> http://aaa.bbb.ccc/1/ 这样我们首先会想到使用`.htaccess` 进行重定向,可实践后发现不可行,原因见:stackoverflow
# RewriteRule /ccc/(\d+)(.*) http://aaa.bbb/ccc/$1 [NE]
RewriteRule /ccc/(\d+).#.(.*) http://aaa.bbb/ccc/$1 [NE]
于是退而求其次,用下面的js完成:
if(window.location.hash.split('-')[0] == '#part')
window.location.href = window.location.href.split('#')[0];
情形3:
锚点和URL的字符串统一关系以及平滑滑动的动画需求,可以看下这段小script的demo:
https://github.com/hzlzh/Anchor-Scroll
锚点滑动jq 关于HTML锚点定位几个不同场景的解决方案
最新推荐文章于 2023-02-08 18:57:26 发布