scrollintoview方法滚动距离顶部距离

发布于:2024-04-27 ⋅ 阅读:(32) ⋅ 点赞:(0)

scrollIntoView 方法是 DOM API 的一部分,用于将元素滚动到视图中。这个方法接收一个布尔值参数 alignToTop,指示是否需要滚动到视图的顶部。

以下是如何使用 scrollIntoView 方法的示例代码:

// 获取需要滚动的元素
const element = document.getElementById('some-element-id');
 
// 滚动到视图中,如果元素高度超过视口,则滚动到视图顶部
element.scrollIntoView(true);
 
// 或者使用简写形式,效果相同
element.scrollIntoView();
 
// 如果你想使用动画滚动效果,可以使用 smooth 选项
element.scrollIntoView({ behavior: 'smooth', block: 'start' });
 
// 如果你想要平滑的滚动效果并且确保元素滚动到视图顶部
element.scrollIntoView({ behavior: 'smooth', block: 'start', inline: 'nearest' });

 以下是一个示例:

<template>
    <div class="content">
        <div class="box1"></div>
        <div class="box2"></div>
        <div class="box3">
            <div class="son" @click="btn">ssss</div>
            <div class="son-ul" v-for="index in 30">1111</div>
        </div>
    </div>
</template>

<script setup lang="ts">
import { ref } from 'vue'

const btn = ()=>{
    const contentDom:any = document.querySelector('.box3');
    contentDom.scrollIntoView({ behavior: 'smooth', block: 'start' });//start
}
</script>

<style scoped lang="less">
.content{
    width: 100vw;
    height: 100vh;
    background-color: aliceblue;
    div{
        width: 100%;
        height: 150px;
    }
    .box1{
        background-color: aquamarine;
    }
    .box2{
        background-color: skyblue;
    }
    .box3{
        height: auto;
        .son{
            width: 100%;
            height: 60px;
            background-color: pink;
        }
        .son-ul{
            width: 100%;
            height: 20px;
            background-color: blanchedalmond;
            margin-top: 10px;
        }
    }
}
</style>