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

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

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

or

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

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


当前回答

Vue.js 2解决方案…添加一个简单的data属性来强制更新:

  const app = new Vue({
  ...

  , updated: function() {
           this.$nextTick(function() {
           var uri = window.location.href
           var anchor = ( uri.indexOf('#') === -1 ) ? '' : uri.split('#')[1]
           if ( String(anchor).length > 0 && this.updater === 'page_load' ) {
              this.updater = "" // only on page-load !
              location.href = "#"+String(anchor)
           }
         })
        }
     });
     app.updater = "page_load"

 /* Smooth scrolling in CSS - it works in HTML5 only */
 html, body {
     scroll-behavior: smooth;
 }

其他回答

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

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

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

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

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

在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'到任何你想要动画的链接

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

Vue.js 2解决方案…添加一个简单的data属性来强制更新:

  const app = new Vue({
  ...

  , updated: function() {
           this.$nextTick(function() {
           var uri = window.location.href
           var anchor = ( uri.indexOf('#') === -1 ) ? '' : uri.split('#')[1]
           if ( String(anchor).length > 0 && this.updater === 'page_load' ) {
              this.updater = "" // only on page-load !
              location.href = "#"+String(anchor)
           }
         })
        }
     });
     app.updater = "page_load"

 /* Smooth scrolling in CSS - it works in HTML5 only */
 html, body {
     scroll-behavior: smooth;
 }