我想让浏览器通过使用JavaScript将页面滚动到给定的锚点。

我已经在HTML代码中指定了一个名称或id属性:

 <a name="anchorName">..</a>

or

 <h1 id="anchorName2">..</h1>

我希望获得与您通过导航到http://server.com/path#anchorName所获得的相同效果。应该滚动页面,使锚点靠近页面可见部分的顶部。


当前回答

很好的解决方案由jAndy,但平滑滚动似乎有问题在Firefox中工作。

在Firefox中也可以这样编写。

(function($) {
    $(document).ready(function() {
         $('html, body').animate({
           'scrollTop':   $('#anchorName2').offset().top
         }, 2000);
    });
})(jQuery);

其他回答

CSS-Tricks的解决方案不再适用于jQuery 2.2.0。它将抛出一个选择器错误:

JavaScript运行时错误:语法错误,无法识别表达式:a[href*=#]:not([href=#])

我通过改变选择器来修复它。完整的片段如下:

$(function() {
  $("a[href*='#']:not([href='#'])").click(function() {
    if (location.pathname.replace(/^\//,'') == this.pathname.replace(/^\//,'') && location.hostname == this.hostname) {
    var target = $(this.hash);
    target = target.length ? target : $('[name=' + this.hash.slice(1) +']');
    if (target.length) {
      $('html,body').animate({
        scrollTop: target.offset().top
      }, 1000);
      return false;
    }
  }
 });
});

大多数答案都不必要地复杂。

如果你只想跳转到目标元素,你不需要JavaScript:

# the link:
<a href="#target">Click here to jump.</a>

# target element:
<div id="target">Any kind of element.</div>

如果你想动画地滚动到目标,请参考5hahiL的答案。

jQuery(“[href ^ = ' # ']”).click(函数(){ jQuery (html、身体).animate ({ jQuery(jQuery(this).attr('href')).offset().top }, 1000); 返回错误; });

这是一个将页面滚动到锚点的工作脚本。 要设置它,只需给锚链接一个与要滚动到的锚的name属性匹配的id。

<script>
    jQuery(document).ready(function ($){
        $('a').click(function (){
            var id = $(this).attr('id');
            console.log(id);
            if ( id == 'cet' || id == 'protein' ) {
                $('html, body').animate({ scrollTop: $('[name="' + id + '"]').offset().top}, 'slow');
            }
        });
    });
</script>

简单的方式:

var element_to_scroll_to = document.getElementById('anchorName2');
// Or:
var element_to_scroll_to = document.querySelectorAll('.my-element-class')[0];
// Or:
var element_to_scroll_to = $('.my-element-class')[0];
// Basically `element_to_scroll_to` just have to be a reference
// to any DOM element present on the page
// Then:
element_to_scroll_to.scrollIntoView();