如何将 HTML 页面滚动到给定的锚点

问题描述 投票:0回答:17

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

我在 HTML 代码中指定了

name
id
属性:

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

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

我希望获得与导航至

http://server.com/path#anchorName
相同的效果。应滚动页面,以便锚点位于页面可见部分的顶部附近。

javascript jquery html scroll anchor
17个回答
408
投票
function scrollTo(hash) {
    location.hash = "#" + hash;
}

根本不需要 jQuery!


278
投票

更简单:

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

127
投票

81
投票

2018 年至今纯 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
的支持效果更好。

详细了解方法


39
投票

jAndy 的解决方案很棒,但平滑滚动似乎在 Firefox 中出现问题。

这种方式在 Firefox 中也适用。

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

35
投票

让浏览器将页面滚动到给定锚点的最简单方法是在

style.css
文件中添加 *{scroll-behavior: smooth;},并在 HTML 导航中使用
#NameOfTheSection

*{scroll-behavior: smooth;}
<a href="#scroll-to">Click to Scroll<a/>

<p>other sections</p>
<p>other sections</p>
<p>other sections</p>
<p>other sections</p>
<p>other sections</p>
<p>other sections</p>
<p>other sections</p>
<p>other sections</p>
<p>other sections</p>
<p>other sections</p>
<p>other sections</p>
<p>other sections</p>
<p>other sections</p>

<section id="scroll-to">
<p>it will scroll down to this section</p>
</section>


30
投票

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

29
投票

这是一个没有 jQuery 的纯 JavaScript 解决方案。它已在 Chrome 和 Internet Explorer 上进行了测试,但未在 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/


18
投票

平滑滚动到合适位置

获取正确

y
坐标并使用
window.scrollTo({top: y, behavior: 'smooth'})

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

window.scrollTo({top: y, behavior: 'smooth'});

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

5
投票

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

5
投票

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

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

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

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

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


4
投票

这有效:

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

  e.preventDefault();

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

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

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

  }, 2000);

});

https://jsfiddle.net/68pnkfgd/

只需将“滚动”类添加到您想要设置动画的任何链接


3
投票

jQuery("a[href^='#']").click(function(){
    jQuery('html, body').animate({
        scrollTop: jQuery( jQuery(this).attr('href') ).offset().top
    }, 1000);
    return false;
});


3
投票

这是一个工作脚本,会将页面滚动到锚点。 要进行设置,只需为锚点链接提供一个与您要滚动到的锚点的名称属性相匹配的 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>

1
投票

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

1
投票

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

  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;
 }
© www.soinside.com 2019 - 2024. All rights reserved.