jQuery:在调用URL时滚动到锚点,替换浏览器行为

bj.*_*bj. 14 anchor jquery scroll smooth

我已经知道了jQuery插件ScrollTo,但到目前为止我还没有找到任何方法来实现以下内容:

用户访问我的网站(通过键入,而不是通过单击我页面上的链接)domain.com/bla.php#foo

并且锚"#foo"存在.现在我希望用户的浏览器不会自动滚动到"#foo",而是我想要平滑滚动,以便元素'#foo'位于视图的中间而不是在绝对的顶部位置用户查看.

谢谢到目前为止!

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)


Vik*_*ala 6

我对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的用户,行为将保持不变.