How to scroll HTML page to given anchor?

后端 未结 17 1777
醉梦人生
醉梦人生 2020-11-22 08:55

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

相关标签:
17条回答
  • 2020-11-22 08:59

    Most answers are unnecessarily complicated.

    If you just want to jump to the target element, you don't need JavaScript:

    # the link:
    <a href="#target">Click here to jump.</a>
    
    # target element:
    <div id="target">Any kind of element.</div>
    

    If you want to scroll to the target animatedly, please refer to @Shahil's answer.

    0 讨论(0)
  • 2020-11-22 09:00

    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;
        }
      }
     });
    });
    
    0 讨论(0)
  • 2020-11-22 09:06

    Smoothly scroll to the proper position (2019)

    Get correct y coordinate and use 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

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

    const yOffset = -10; 
    
    window.scrollTo({top: y + yOffset, behavior: 'smooth'});
    
    0 讨论(0)
  • 2020-11-22 09:06

    the easiest way to to make the browser to scroll the page to a given anchor is to type in your style.css *{scroll-behavior: smooth;} and in your html navigation use #NameOfTheSection

    *{scroll-behavior: smooth;}
    <a href="#scroll-to">Home<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>

    0 讨论(0)
  • 2020-11-22 09:07

    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.

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

    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()
        })
    }
    
    0 讨论(0)
  • 2020-11-22 09:07

    I know this is question is really old, but I found an easy and simple jQuery solution in css-tricks. That's the one I'm using now.

    $(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;
          }
        }
      });
    });
    
    0 讨论(0)
提交回复
热议问题