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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3163615/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 03:30:16  来源:igfitidea点击:

How to scroll HTML page to given anchor?

javascriptjqueryhtmlscrollanchor

提问by Juha Syrj?l?

I'd like to make the browser to scroll the page to a given anchor, just by using JavaScript.

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

I have specified a nameor idattribute in my HTML code:

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

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

or

或者

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

I'd like to get the same effect as you'd get by navigating to http://server.com/path#anchorName. The page should be scrolled so that the anchor is near the top of the visible part of the page.

我希望获得与导航到http://server.com/path#anchorName. 应该滚动页面,以便锚点靠近页面可见部分的顶部。

回答by Dean Harding

function scrollTo(hash) {
    location.hash = "#" + hash;
}

No jQuery required at all!

根本不需要jQuery!

回答by Armando Pérez Marqués

Way simpler:

方式更简单:

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

回答by jAndy

You can use jQuerys .animate(), .offset()and scrollTop. Like

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

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

example link: http://jsbin.com/unasi3/edit

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

If you don't want to animate use .scrollTop()like

如果你不想动画使用.scrollTop()

$(document.body).scrollTop($('#anchorName2').offset().top);

or javascripts native location.hashlike

或 javascripts 本机之location.hash类的

location.hash = '#' + anchorid;

回答by 5hahiL

Great solution by jAndy, but the smooth scroll seems to be having issues working in firefox.

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

Writing it this way works in Firefox as well.

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

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

回答by Илья Зеленько

2018-2020 Pure js:

2018-2020 纯js:

There is a very convenient way to scroll to the element:

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

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

But as far as I understand he does not have such good support as the options below.

但据我所知,他没有以下选项的良好支持。

enter image description here

在此处输入图片说明

Learn more about the method.

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



If it is necessary that the element is in the top:

如果元素必须位于顶部:

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

Demonstration example on Codepen

Codepen 上的演示示例



If you want the element to be in the center:

如果您希望元素位于中心:

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

Demonstration example on Codepen

Codepen 上的演示示例



Support:

支持:

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

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

They write that scrollis the same method as scrollTo, but support shows better in scrollTo.

他们编写scroll的方法与 相同scrollTo,但在scrollTo.

More about the method

关于方法的更多信息

回答by Michael Whinfrey

A pure javascript solution without JQuery. Tested on Chrome & I.e, not tested on IOS

没有 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;
  }
}

demo: https://jsfiddle.net/jd7q25hg/12/

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

回答by coco puffs

In 2018, you don't need jQuery for something simple like this. The built in scrollIntoView()method supports a "behavior" property to smoothly scroll to any element on the page. You can even update the browser URL with a hash to make it bookmarkable.

在 2018 年,你不需要 jQuery 来完成这样的简单事情。内置scrollIntoView()方法支持“ behavior”属性以平滑滚动到页面上的任何元素。您甚至可以使用哈希值更新浏览器 URL 以使其可加入书签。

From this tutorial on scrolling HTML Bookmarks, here is a native way to add smooth scrolling to all anchor links on your page automatically:

关于滚动 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()
????})
}

回答by Arseniy-II

Smoothly scroll to the proper position (2019)

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

Get correctycoordinate and use window.scrollTo({top: y, behavior: 'smooth'})

获取正确的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'});

With offset

有偏移

scrollIntoViewis a good option too but it may not works perfectly in some cases. For example when you need additional offset. With scrollToyou just need to add that offset like this:

scrollIntoView也是一个不错的选择,但在某些情况下可能无法完美运行。例如,当您需要额外的 offset 时。有了scrollTo你只需要添加一个这样的补偿:

const yOffset = -10; 

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

回答by Bill Shihara

The solution from CSS-Tricks no longer works in jQuery 2.2.0. It will throw a selector error:

CSS-Tricks 的解决方案不再适用于 jQuery 2.2.0。它会抛出一个选择器错误:

JavaScript runtime error: Syntax error, unrecognized expression: a[href*=#]:not([href=#])

JavaScript 运行时错误:语法错误,无法识别的表达式:a[href*=#]:not([href=#])

I fixed it by changing the selector. The full snippet is this:

我通过更改选择器来修复它。完整的片段是这样的:

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

回答by cactis

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