知识总结——Vue非a标签平滑的锚点定位

126 阅读1分钟

方法:

  1. 锚点设置id
  2. 点击元素添加点击事件,使用scrollIntoView() 方法

el.scrollIntoView() 将元素对用户可见(滚动到可视区),参数alignToTop或scrollIntoViewOptions 这里使用第二个,其中包括三个属性:

  • behavior

  • 定义动画过渡, "auto"或 其中"smooth" 之一。默认为 效果"auto"

  • block

  • 定义垂直方向的书签,  "start",  "center",  "end", 或 其中"nearest"之一。默认为 "start"

  • inline 

  • 自定义水平的方向,  "start",  "center",  "end", 或 "nearest"其中一个。默认为 收藏"nearest"

上代码:

    <template>
        <div>
            <!-- 点击元素 -->
            <div @click="changePoint(index)" v-for="(item, index) in list" :key="index">
                点击{{ index }}
            </div>
            <!-- 锚点:设置id -->
            <span :id="`point${index}`" v-for="(item, index) in list" :key="index">item</span>
        </div>
    </template>

    <script>
    export default {
        data() {
            return {
                list: [1, 2, 3]
            };
        },
        methods: {
            changePoint(index) {
                const el = document.querySelector(`#point${index}`);
                el.scrollIntoView({
                    block: 'center',
                    behavior: 'smooth'
                });
            }
        }
    };
    </script>

    <style></style>