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

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

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

or

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

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


当前回答

$(document).ready ->
  $("a[href^='#']").click ->
    $(document.body).animate
      scrollTop: $($(this).attr("href")).offset().top, 1000

其他回答

$(document).ready ->
  $("a[href^='#']").click ->
    $(document.body).animate
      scrollTop: $($(this).attr("href")).offset().top, 1000

在2018年,你不需要jQuery来做这样简单的事情。内置scrollIntoView()方法支持一个“behavior”属性,可以平滑地滚动到页面上的任何元素。您甚至可以用散列更新浏览器URL,使其可收藏。

从这个关于滚动HTML书签的教程中,这里有一个本地的方法来自动添加平滑滚动到页面上的所有锚链接:

let anchorlinks = document.querySelectorAll('a[href^="#"]')
 
for (let item of anchorlinks) { // relitere 
    item.addEventListener('click', (e)=> {
        let hashval = item.getAttribute('href')
        let target = document.querySelector(hashval)
        target.scrollIntoView({
            behavior: 'smooth',
            block: 'start'
        })
        history.pushState(null, null, hashval)
        e.preventDefault()
    })
}

如此:

$('.scroll').on("click", function(e) {

  e.preventDefault();

  var dest = $(this).attr("href");

  $("html, body").animate({

    'scrollTop':   $(dest).offset().top

  }, 2000);

});

https://jsfiddle.net/68pnkfgd/

只需添加类'scroll'到任何你想要动画的链接

我在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;
      }
    }
  });
});

要让浏览器滚动页面到给定的锚点,最简单的方法是在style.css文件中添加*{scroll-behavior: smooth;},在HTML导航中使用# nameofsection。

* {scroll-behavior:光滑;} <a href="# Scroll -to">点击滚动<a/> < p > < / p >其他部分 < p > < / p >其他部分 < p > < / p >其他部分 < p > < / p >其他部分 < p > < / p >其他部分 < p > < / p >其他部分 < p > < / p >其他部分 < p > < / p >其他部分 < p > < / p >其他部分 < p > < / p >其他部分 < p > < / p >其他部分 < p > < / p >其他部分 < p > < / p >其他部分 <节id = "滚动到" > <p>它将向下滚动到这个部分</p> < / >节