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

Juh*_*älä 242 html javascript anchor jquery scroll

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

我在HTML代码中指定了一个nameid属性:

 <a name="anchorName">..</a>
Run Code Online (Sandbox Code Playgroud)

要么

 <h1 id="anchorName2">..</h1>
Run Code Online (Sandbox Code Playgroud)

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

Dea*_*ing 329

function scrollTo(hash) {
    location.hash = "#" + hash;
}
Run Code Online (Sandbox Code Playgroud)

根本不需要jQuery!

  • 这实际上并没有滚动,它只是跳跃.此时你也可以直接链接到锚点"<a href="#anchorName">链接</a>" (83认同)
  • 请注意,这只会工作一次.一旦设置了散列,页面将不会滚动到相同的散列,除非您将其更改为虚拟散列,然后再次设置它. (47认同)
  • 您不应该使用scrollTo,因为它已被全局窗口对象使用.此参数也不应该命名为hash,因为location.hash也是定义的.您可以使用以下代码:`function scrollToHash(hashName){location.hash ="#"+ hashName; }` (12认同)
  • 如果您设置“scroll-behavior: smooth;”,这会滚动 在 html 元素上 (11认同)
  • @MarkusZeller,为什么不应该将参数称为哈希?它不会与位置发生碰撞,是吗? (3认同)

Arm*_*ués 214

方式更简单:

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();
Run Code Online (Sandbox Code Playgroud)

  • 我起初认为Mandx是在拖钓,然后我尝试了这个并且它有效.除了我之外,我之前从未遇到过这种方法.[此方法的Mozilla文档](https://developer.mozilla.org/en-US/docs/DOM/element.scrollIntoView).此外,它似乎在浏览器中得到了很好的支持. (21认同)
  • 这是一个干净的解决方案,但是现在它不允许任何调整,它做了一个硬滚动.有一个实验参数`scrollIntoViewOptions`有一个`behavior:"smooth"`选项,但它目前只与Firefox兼容. (5认同)
  • 我有很多问题,jquery解决方案没有滚动.这给我带来了很多挫折感. (2认同)
  • **警告!** 如果上面的 div 包含浮动元素并且无法轻松确定其大小,则此方法可能会出现问题。 (2认同)
  • 如果你认为你想要平滑滚动,你应该使用`document.getElementById("xyz").scrollIntoView({block:"nearest",behavior:"smooth"});`,这样用户就不会得到强制平滑滚动,如果他们已在浏览器设置中禁用了该功能。Safari 不支持此功能,因此它只会捕捉到正确的位置,而不会显示动画。您应该使用它而不是滚动到给定的像素偏移量,因为这会自动遵循例如“scroll-margin”属性。重新实现对“scroll-margin”的支持将非常复杂。 (2认同)

jAn*_*ndy 122

您可以使用jQuerys .animate() ,.offset()scrollTop.喜欢

$(document.body).animate({
    'scrollTop':   $('#anchorName2').offset().top
}, 2000);
Run Code Online (Sandbox Code Playgroud)

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

如果您不想使用.scrollTop()之类的动画

$(document.body).scrollTop($('#anchorName2').offset().top);
Run Code Online (Sandbox Code Playgroud)

或javascripts原生的location.hash喜欢

location.hash = '#' + anchorid;
Run Code Online (Sandbox Code Playgroud)

  • jQuery.scrollTop在Chrome中对我来说根本不起作用:( (6认同)
  • @CodeJoust - 我在jQuery团队,我已经阅读了很多次,是的`$("#selector")`是优化的但是`$("#selector,a [name ='selector']") `不会很快进行同样的优化.我想我2.5岁的评论听起来有点奇怪."优化"是避免`a [name ='selector']`搜索,如果它找到id,而不是优化搜索id. (3认同)

5ha*_*hiL 31

jAndy提供了很好的解决方案,但顺畅的滚动似乎在firefox中有问题.

以这种方式编写它也适用于Firefox.

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


小智 25

没有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;
  }
}
Run Code Online (Sandbox Code Playgroud)

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

  • 这应该是公认的答案:它是一个纯 js 示例并且它实现了所需的滚动动画效果。我将超时值调整为 20,它可以完美运行。 (2认同)
  • IOS下可以用,刚刚测试过。 (2认同)

Иль*_*ько 20

2018年纯粹的js:

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

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.
})
Run Code Online (Sandbox Code Playgroud)

但据我了解,他没有下面的选项那么好的支持.

在此输入图像描述

详细了解该方法.


如果元素必须在顶部:

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

window.scrollTo({
  top, // scroll so that the element is at the top of the view
  behavior: 'smooth' // smooth scroll
})
Run Code Online (Sandbox Code Playgroud)

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
});
Run Code Online (Sandbox Code Playgroud)

Codepen上的演示示例


支持:

введитесюдаописаниеизображения

他们写scroll的方法与方法相同scrollTo,但支持显示更好scrollTo.

更多关于该方法


coc*_*ffs 15

在2018年,你不需要像这样简单的jQuery.内置[scrollIntoView()][1]方法支持" 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()
    })
}
Run Code Online (Sandbox Code Playgroud)

  • 消除对 jQuery 依赖的优秀答案 (3认同)

小智 11

让浏览器将页面滚动到给定锚点的最简单方法是*{scroll-behavior: smooth;}style.css文件和 HTML 导航中添加 use #NameOfTheSection

*{scroll-behavior: smooth;}
Run Code Online (Sandbox Code Playgroud)
<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>
Run Code Online (Sandbox Code Playgroud)

  • 这个 CSS 方法对我来说非常有用,而且超级优雅! (2认同)

Ars*_*-II 10

平滑滚动到正确位置(2019)

获取正确的 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'});
Run Code Online (Sandbox Code Playgroud)

有偏移

scrollIntoView也是一个不错的选择,但在某些情况下可能无法完美运行。例如,当您需要其他偏移量时。与scrollTo您只需要添加这样的偏移量:

const yOffset = -10; 

window.scrollTo({top: y + yOffset, behavior: 'smooth'});
Run Code Online (Sandbox Code Playgroud)


cac*_*tis 5

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


Bri*_*ian 5

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

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

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

# target element:
<div id="target">Any kind of element.</div>
Run Code Online (Sandbox Code Playgroud)

如果您想要动画滚动到目标,请参阅@ Shahil的答案.


Bil*_*ara 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;
    }
  }
 });
});
Run Code Online (Sandbox Code Playgroud)