Usually a complete page can contain multiple screens of content, so we often need to scroll through the page to read the content on the page. There are some clickable links or buttons on the page, click to switch to the specified location of the page, today introduces several ways to achieve.

This is the 20th day of my participation in the August Text Challenge.More challenges in August

Pure HTML implementation (anchor points)

Generally contains two parts:

  • The anchor
  • Anchor the object
<a href="#anchorName">Click to jump to the current page to specify the anchor point</a>
<a name="anchorName">The name anchor</a>
<p id="anchorName">Id anchor</p>
Copy the code

Effect: When you click on the first A TAB, the top of the page scrolls to the next A TAB. Features: No buffering, mediocre experience, and “#anchorName” added to the URL. This can contaminate routes in SPA applications. So the native way may not be the best way to deal with, of course, the advantage is simpler.

Js assist (window.scrollto method)

Grammar:

window.scrollTo(options)
options:{
    left:number,
    top:number,
    behavior:"smooth"|"instant"
}
Copy the code

Here’s a request: click a button to scroll an element to the top of the screen.

The analysis has the following steps:

  • Get the distance from the element to the top of the document,offsetTopReturns the current element relative to itoffsetParentDistance from the top of the element.
  • Get the distance from the top of the document by summing it up in a recursive loop

The specific implementation code is as follows:

function heightToTop(ele){
    //ele specifies the DOM node to jump to
    let root = document.body;
    let height = 0;
    do{
        height += ele.offsetTop;
        ele = ele.offsetParent;
    }while( ele ! == root )return height;
}
// when a button is clicked
someBtn.addEventListener('click'.function(e){
    window.scrollTo({
        top:heightToTop(e.target),
        behavior:'smooth'})})Copy the code

Note: Window.scrollto can only change the roll distance of the outermost container. If you abscond to a div on your page, that div has its own scrolling distance, it will not be affected.

ScrollTop properties

Change the scrolling distance of the container directly by setting the scrollTop property.

  • Set the rolling distance of the outermost scrollable container:document.documentElement.scrollTop = 100
  • When the outermost scroll container of the page escapes a scroll container:HTMLElement.scrollTop = 100

// when a button is clicked
someBtn.addEventListener('click'.function(e){
    const heightToTop = heightToTop(e.target);
    document.documentElement.scrollTop = heightToTop;
})
Copy the code

The last

Finally, thanks for reading!