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

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

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

or

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

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


当前回答

在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()
    })
}

其他回答

平稳滚动到适当的位置

得到正确的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'});

你可以使用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;

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

这是一个将页面滚动到锚点的工作脚本。 要设置它,只需给锚链接一个与要滚动到的锚的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>

2018-2020纯JavaScript:

有一个非常方便的方法来滚动到元素:

el.scrollIntoView({
  behavior: 'smooth', // smooth scroll
  block: 'start' // the upper border of the element will be aligned at the top of the visible part of the window of the scrollable area.
})

但据我了解,它并没有下面的选项那么好的支持。

了解更多关于该方法的信息。


如果元素必须在顶部:

const element = document.querySelector('#element')
const topPos = element.getBoundingClientRect().top + window.pageYOffset

window.scrollTo({
  top: topPos, // scroll so that the element is at the top of the view
  behavior: 'smooth' // smooth scroll
})

CodePen上的演示示例


如果你想让元素在中间:

const element = document.querySelector('#element')
const rect = element.getBoundingClientRect() // get rects(width, height, top, etc)
const viewHeight = Math.max(document.documentElement.clientHeight, window.innerHeight || 0);

window.scroll({
  top: rect.top + rect.height / 2 - viewHeight / 2,
  behavior: 'smooth' // smooth scroll
});

CodePen上的演示示例


支持:

他们写道,scroll是与scrollTo相同的方法,但在scrollTo中支持更好。

关于方法的更多信息。