Jan*_*oom 21
如果你没有创建实际的锚点foo,而是创建一个id为_foo(类似的<a id="_foo">)id的锚点.你可以处理$(document).ready实现这一目标.
像(伪代码)的东西
$(document).ready(function() {
var elem = $('#_' + window.location.hash.replace('#', ''));
if(elem) {
$.scrollTo(elem.left, elem.top);
}
});
Run Code Online (Sandbox Code Playgroud)
我对Jan Jongboom的脚本做了一些改进,所以它现在看起来像这样:
$(document).ready(function () {
// replace # with #_ in all links containing #
$('a[href*=#]').each(function () {
$(this).attr('href', $(this).attr('href').replace('#', '#_'));
});
// scrollTo if #_ found
hashname = window.location.hash.replace('#_', '');
// find element to scroll to (<a name=""> or anything with particular id)
elem = $('a[name="' + hashname + '"],#' + hashname);
if(elem) {
$(document).scrollTo(elem, 800);
}
});
Run Code Online (Sandbox Code Playgroud)
它会更改链接中的所有锚点,因此对于没有javascript的用户,行为将保持不变.