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 box"></div><div class="box2 box"></div><div class="box3"><div class="son"><ul><li @click="btn(0)">TabA</li><li @click="btn(1)">TabB</li></ul><div class="bg" :class="transbg ? 'transbg' : ''"></div></div><div class="son-ul"><div class="son-li" v-for="index in 50">{{ index }}{{ index }}{{ index }}{{ index }}{{ index }}</div></div></div></div>
</template><script setup lang="ts">
import { ref } from 'vue'const transbg = ref<any>(false)const btn = (val:any)=>{const contentDom:any = document.querySelector('.son');contentDom.scrollIntoView({ behavior: 'smooth', block: 'start' });//startif(val == 1){transbg.value = true} else {transbg.value = false}
}
</script><style scoped lang="less">
.content{width: 100vw;height: 100vh;background-color: aliceblue;overflow-y: scroll;.box{width: 100%;height: 150px;}.box1{background-color: aquamarine;}.box2{background-color: skyblue;}.box3{.son{width: 100%;height: 60px;background-color: pink;position: sticky;top: 0px;display: flex;justify-content: center;align-items: center;ul{width: 70%;height: 50px;background-color: azure;border-radius: 25px;list-style-type: none;display: flex;justify-content: center;align-items: center;position: relative;li{flex: 1;line-height: 30px;text-align: center;height: 35px;z-index: 10;}}.bg{position: absolute;left:18%;width: 28%;height: 40px;background-color: rgb(176, 105, 17);border-radius: 20px;transition: all .5s;}.transbg{left: 54%;}}.son-ul{scroll-behavior: smooth;width: 100%;.son-li{height: 20px;background-color: blanchedalmond;margin-top: 10px;}}}
}
</style>