Click on the title to scroll to the specified position

When we want to click on an element on the page to scroll it to a specified position, there are many methods we can use; the more straightforward one is to use the anchor point that comes with the a tag, as shown below, but this way to jump to the page The display effect will be stiff;

a tag example:

<template>
  <div>
    <a href="#test">显示文本</a>
    <div style="height:2000px"> </div>

    <div>
      <h2 id="test">这是一个标题</h2>
      <p>Lorem ipsum dolor sit amet consectetur adipisicing elit. Consequatur officia         sapiente delectus libero odio, dicta ipsum sunt eveniet molestias dolore sint, modi suscipit, dignissimos consequuntur autem repudiandae illum quidem sequi?</p>
    </div>

    <div style="height:2000px"> </div>
  </div>
</template>

So we can use the scrollIntoView() method, which scrolls the element's parent container so that the element on which scrollIntoView() is called is visible to the user.

scrollIntoView() method example:

<template>
  <div>
    <div @click="showNode">显示文本</div>
    <div style="height:2000px"> </div>
    <div id="text_node">
      <h2 id="test">这是一个标题</h2>
      <p>Lorem ipsum dolor sit amet consectetur adipisicing elit. Consequatur officia sapiente delectus libero odio, dicta ipsum sunt eveniet molestias dolore sint, modi suscipit, dignissimos consequuntur autem repudiandae illum quidem sequi?</p>
    </div>
    <div style="height:2000px"> </div>
  </div>
</template>

<script>
export default {
  methods: {
    showNode() {
      document.getElementById('text_node').scrollIntoView() // 默认滚动至节点置顶
      document.getElementById('text_node').scrollIntoView(false) // 默认滚动至节点显示
      document.getElementById('text_node').scrollIntoView({ behavior: "smooth", block: "end", inline: "nearest" }); // 见下文
    }
  }
}
</script>

Use of scrollIntoView() method

The scrollIntoView( [alignToTop,scrollIntoViewOptions] ) method can carry up to two parameters;

 alignToTop optional

      If true, the top of the element will be aligned with the top of the visible area of ​​the scroll area. This is the default value for this parameter.

      If false, the bottom of the element will be aligned with the bottom of the visible area of ​​the scroll area.

 scrollIntoViewOptions optional

      behavior optional

            Define the animation transition effect, one of auto or smooth. The default is auto.

      block optional

            Defines the vertical alignment, one of start, center, end or nearest. The default is start.

      inline optional

            Defines the horizontal alignment, one of start, center, end or nearest. The default is nearest.

Summarize:

        The scrollIntoView() method can not only control the display position, but also set the animation effect when scrolling excessively, which will provide a better user experience.

Guess you like

Origin blog.csdn.net/m0_66675766/article/details/131106647
Recommended