How to scroll HTML page to given anchor?

2018-12-31 10:02发布

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

I have specified a name or id attribute in my HTML code:

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

14条回答
后来的你喜欢了谁
2楼-- · 2018-12-31 10:11

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

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

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

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

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

or javascripts native location.hash like

location.hash = '#' + anchorid;
查看更多
琉璃瓶的回忆
3楼-- · 2018-12-31 10:11

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

JavaScript runtime error: Syntax error, unrecognized expression: 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;
    }
  }
 });
});
查看更多
其实,你不懂
4楼-- · 2018-12-31 10:12

2018 Pure 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.scrollTo({
  top, // scroll so that the element is at the top of the view
  behavior: 'smooth' // smooth scroll
})

Demonstration example on 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


Support:

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

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

More about the method

查看更多
ら面具成の殇う
5楼-- · 2018-12-31 10:14

This works:

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

  e.preventDefault();

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

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

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

  }, 2000);

});

https://jsfiddle.net/68pnkfgd/

Just add the class 'scroll' to any links you wish to animate

查看更多
荒废的爱情
6楼-- · 2018-12-31 10:14

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

查看更多
不流泪的眼
7楼-- · 2018-12-31 10:16
$(document).ready ->
  $("a[href^='#']").click ->
    $(document.body).animate
      scrollTop: $($(this).attr("href")).offset().top, 1000
查看更多
登录 后发表回答