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

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

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

or

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

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


当前回答

我在CSS-Tricks上找到了一个简单的jQuery解决方案。这就是我现在用的。

$(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;
      }
    }
  });
});

其他回答

你可以使用jQuery的.animate(), .offset()和scrollTop。就像

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

示例链接:http://jsbin.com/unasi3/edit

如果你不想动画,使用.scrollTop():

$(document.body).scrollTop($('#anchorName2').offset().top);

或者JavaScript的原生位置。散列:

location.hash = '#' + anchorid;

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

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

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

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

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

平稳滚动到适当的位置

得到正确的y坐标并使用window。scrollTo({top: y,行为:'平滑'})

const id = 'anchorName2';
const yourElement = document.getElementById(id);
const y = yourElement.getBoundingClientRect().top + window.pageYOffset;

window.scrollTo({top: y, behavior: 'smooth'});
function scrollTo(hash) {
    location.hash = "#" + hash;
}

根本不需要jQuery !

这是一个没有jQuery的纯JavaScript解决方案。它在Chrome和ie浏览器上进行了测试,但没有在iOS上进行测试。

function ScrollTo(name) {
  ScrollToResolver(document.getElementById(name));
}

function ScrollToResolver(elem) {
  var jump = parseInt(elem.getBoundingClientRect().top * .2);
  document.body.scrollTop += jump;
  document.documentElement.scrollTop += jump;
  if (!elem.lastjump || elem.lastjump > Math.abs(jump)) {
    elem.lastjump = Math.abs(jump);
    setTimeout(function() { ScrollToResolver(elem);}, "100");
  } else {
    elem.lastjump = null;
  }
}

演示:https://jsfiddle.net/jd7q25hg/12/