js:scroll smoothly scrolls the page or element to the top or bottom of the program summary

Preparation knowledge:

  • scrollWidth: is the width of the entire content of the element, including content that is not visible on the screen due to overflow
  • scrollHeight: is the height of the entire content of the element, including content that is not visible on the screen due to overflow
  • scrollTop: The distance between the vertical scroll bar and the topmost element
  • scrollLeft: The distance from the horizontal scroll bar to the leftmost of the element

1、CSS的scroll-behavior

grammar

scroll-behavior: auto | smooth | inherit | unset

Parameters
- smooth: Indicates that the scrolling is smooth, with a transition effect
- auto: no transition effect, flashing by.

key code

html, body {
    
    
  scroll-behavior: smooth;
}

sample code

<style>
  * {
      
      
    margin: 0;
    padding: 0;
    text-align: center;
  }

  html {
      
      
    scroll-behavior: smooth;
  }

  .btn {
      
      
    margin-bottom: 20px;
  }

  .box {
      
      
    margin-top: 20px;
    height: 1500px;
    line-height: 1500px;
    background-color: #95e1d3;
  }
</style>

<div class="box" id="box">Box</div>

<a href="#box" class="btn">回到顶部</a>

Online demo: https://mouday.github.io/front-end-demo/scroll/scroll-behavior.html

You can judge whether to support css scroll-behaviorattributes through js

function isSuportScrollBehavior() {
    
    
    return !(typeof window.getComputedStyle(document.body).scrollBehavior === 'undefined');
}

2、Element.scrollTop

Set the attribute scrollTopto the element scrollHeightto scroll to the bottom of the element, but there is no animation effect

example

<style>
  * {
      
      
    margin: 0;
    padding: 0;
    text-align: center;
  }

  .btn {
      
      
    margin-top: 20px;
  }

  .box {
      
      
    margin-top: 20px;
    height: 1500px;
    line-height: 1500px;
    background-color: #95e1d3;
  }
</style>

<button id="btn" class="btn">滚动到底部</button>

<div class="box">Box</div>

<script>
  // 滑动底部
  let btn = document.querySelector("#btn");

  btn.addEventListener("click", function () {
      
      
    document.documentElement.scrollTop = document.documentElement.scrollHeight;
  });
</script>

Compatibility

let scrollTop = document.documentElement.scrollTop || document.body.scrollTop;

Online demo: https://mouday.github.io/front-end-demo/scroll/scrollTop.html

3、Element.scroll()/Window.scroll()

The scroll() method is used to 滚动元素go to a specific coordinate

Documentation: https://developer.mozilla.org/zh-CN/docs/Web/API/Element/scroll

grammar

scroll(x-coord, y-coord)
scroll(options)

parameter

  • x-coord The number of pixels along the horizontal axis that you want to display in the upper left corner of the element.

  • y-coord The number of pixels along the vertical axis that you want to display in the upper left corner of the element.

  • options

    • top: Specifies the number of pixels to scroll the window or element along the Y axis.
    • left: Specifies the number of pixels to scroll the window or element along the X axis.
    • behavior:
      • smooth means smooth scrolling and produces transition effects,
      • auto, or the default value, jumps directly to the target location with no transition effects.

example

<style>
  * {
      
      
    margin: 0;
    padding: 0;
    text-align: center;
  }

  .btn {
      
      
    margin-top: 20px;
  }

  .box {
      
      
    margin-top: 20px;
    height: 1500px;
    line-height: 1500px;
    background-color: #95e1d3;
  }
</style>

<button id="to-bottom" class="btn">滚动到底部</button>

<div class="box">Box</div>

<button id="tp-top" class="btn">滚动到顶部</button>

<script>
  // 滑动底部
  let toBottom = document.querySelector("#to-bottom");

  toBottom.addEventListener("click", function () {
      
      
    window.scrollTo({
      
      
      top: document.documentElement.scrollHeight,
      behavior: "smooth",
    });
  });

  // 滑动顶部
  let toTop = document.querySelector("#tp-top");

  toTop.addEventListener("click", function () {
      
      
    window.scrollTo({
      
      
      top: 0,
      behavior: "smooth",
    });
  });
</script>

Online demo: https://mouday.github.io/front-end-demo/scroll/scroll.html

4、Element.scrollBy()/Window.scrollBy()

The scrollBy() method is an Element interface that makes an element scroll a specified distance.

Use the same methodElement.scroll()/Window.scroll()

Note: scrollBy (the rollback scroll bar needs to write a negative number, and the others are consistent with scroll)

<style>
  * {
      
      
    margin: 0;
    padding: 0;
    text-align: center;
  }

  .btn {
      
      
    margin-top: 20px;
  }

  .box {
      
      
    margin-top: 20px;
    height: 1500px;
    line-height: 1500px;
    background-color: #95e1d3;
  }
</style>

<button id="to-bottom" class="btn">滚动到底部</button>

<div class="box">Box</div>

<button id="tp-top" class="btn">滚动到顶部</button>

<script>
  // 滑动底部
  let toBottom = document.querySelector("#to-bottom");

  toBottom.addEventListener("click", function () {
      
      
    window.scrollBy({
      
      
      top: document.documentElement.scrollHeight,
      behavior: "smooth",
    });
  });

  // 滑动顶部
  let toTop = document.querySelector("#tp-top");

  toTop.addEventListener("click", function () {
      
      
    window.scrollBy({
      
      
      top: -document.documentElement.scrollHeight,
      behavior: "smooth",
    });
  });
</script>

Online demo: https://mouday.github.io/front-end-demo/scroll/scrollBy.html

5、Element.scrollTo()/Window.scrollTo()

Element's scrollTo() method can make the interface scroll to the specified coordinate position of the given element.

Use the same methodElement.scroll()/Window.scroll()

6、Element.scrollIntoView()

The scrollIntoView() method of the Element interface 滚动元素的父容器makes the element on which scrollIntoView() is called visible to the user.

Documentation: https://developer.mozilla.org/zh-CN/docs/Web/API/Element/scrollIntoView

grammar

scrollIntoView()
scrollIntoView(alignToTop)
scrollIntoView(scrollIntoViewOptions)

parameter

  • alignToTop optional (boolean)

    • true, the top of the element will be aligned with the top of the visible area of ​​the scroll area where it is located. Corresponding scrollIntoViewOptions: {block: “start”, inline: “nearest”}. This is the default value for this parameter.
    • false, the bottom of the element will be aligned with the bottom of the visible area of ​​the scroll area where it is located. The corresponding scrollIntoViewOptions: {block: “end”, inline: “nearest”}.
  • scrollIntoViewOptions optional experimental

    • behavior Optional defines the animation transition effect, one of auto or smooth. The default is auto.
    • block optionally defines the vertical alignment, one of start (top), center (middle), end (bottom) or nearest (nearest point). The default is start.
    • inline Optional defines the horizontal alignment, one of start, center, end or nearest. The default is nearest.
<style>
  * {
      
      
    margin: 0;
    padding: 0;
    text-align: center;
  }

  .btn {
      
      
    margin-top: 20px;
  }

  pre,
  code {
      
      
    text-align: unset;
  }

  .top {
      
      
    margin-top: 20px;
    height: 1500px;
    line-height: 1500px;
    background-color: #95e1d3;
  }

  .box {
      
      
    margin-top: 20px;
    height: 200px;
    line-height: 200px;
    background-color: #eaffd0;
  }
</style>

<button id="btn" class="btn">滚动到Box</button>

<div class="top">TOP</div>

<div class="box">Box</div>

<script>
  let btn = document.querySelector("#btn");

  btn.addEventListener("click", function () {
      
      
    let top = document.querySelector(".box");
    top.scrollIntoView({
      
      
      block: 'start',
      behavior: "smooth",
    });
  });
</script>

Online demo: https://mouday.github.io/front-end-demo/scroll/scrollIntoView.html

7. Custom compatibility scheme

There may be compatibility on some old devices, and a buffer solution supported by multiple devices is collected from the Internet

<style>
  * {
      
      
    margin: 0;
    padding: 0;
    text-align: center;
  }

  .btn {
      
      
    margin-top: 20px;
  }

  .box {
      
      
    margin-top: 20px;
    height: 1500px;
    line-height: 1500px;
    background-color: #95e1d3;
  }
</style>

<button id="to-bottom" class="btn">滚动到底部</button>

<div class="box">Box</div>

<button id="tp-top" class="btn">滚动到顶部</button>

<script>
  // 封装一个回到底部或者顶部的函数
  function scrollToTop(position) {
      
      
    // 使用requestAnimationFrame,如果没有则使用setTimeOut
    if (!window.requestAnimationFrame) {
      
      
      window.requestAnimationFrame = function (callback) {
      
      
        return setTimeout(callback, 20);
      };
    }

    // 获取当前元素滚动的距离
    let scrollTopDistance =
      document.documentElement.scrollTop || document.body.scrollTop;

    function smoothScroll() {
      
      
      console.log('smoothScroll');
      // 如果你要滚到顶部,那么position传过来的就是0,下面这个distance肯定就是负值。
      let distance = position - scrollTopDistance;
      // 每次滚动的距离要不一样,制造一个缓冲效果
      scrollTopDistance = scrollTopDistance + distance / 5;
      // 判断条件
      if (Math.abs(distance) < 1) {
      
      
        window.scrollTo(0, position);
      } else {
      
      
        window.scrollTo(0, scrollTopDistance);
        requestAnimationFrame(smoothScroll);
      }
    }

    smoothScroll();
  }

  // 滑动顶部
  let toTop = document.querySelector("#tp-top");

  toTop.addEventListener("click", function () {
      
      
    // 回到顶部
    scrollToTop(0);
  });

  // 滑动底部
  let toBottom = document.querySelector("#to-bottom");

  toBottom.addEventListener("click", function () {
      
      
    // 滚到底部
    scrollToTop(document.documentElement.scrollHeight - window.innerHeight);
  });
</script>

Online demo: https://mouday.github.io/front-end-demo/scroll/smoothScroll.html

8. Reference articles

  1. JS slides to the top (or bottom) of the page
  2. 2020-06-23 Native js makes dom scroll to the bottom automatically
  3. The methods of manipulating Element to scroll in s are all here‍‍‍
  4. Several options for smooth scrolling to the top or bottom
  5. Perfectly realize a "back to top"
  6. [Frontend] Knowledge points drawn by lazy loading of pictures

Guess you like

Origin blog.csdn.net/mouday/article/details/131678336