1. 實現效果
點擊頂部標簽欄,讓對應的內容出現在可視區域:
2. scrollIntoView ()
scrollIntoView 是一個內置的 JavaScript 方法,用于將元素滾動到視口可見的位置。它通常用于用戶界面中,以便用戶能輕松看到特定的元素。此方法可以應用于任何 DOM 元素,并且有多個參數可以控制滾動行為。
scrollIntoView()
scrollIntoView(alignToTop) // 傳一個布爾值
scrollIntoView(scrollIntoViewOptions) // 傳一個配置項對象
alignToTop(一個布爾值):可選
- 如果為 true,元素的頂端將和其所在滾動區的可視區域的頂端對齊。相應的 scrollIntoViewOptions: {block: “start”, inline: “nearest”}。這是這個參數的默認值。
- 如果為 false,元素的底端將和其所在滾動區的可視區域的底端對齊。相應的 scrollIntoViewOptions: {block: “end”, inline: “nearest”}。
scrollIntoViewOptions(個配置項對象):可選
behavior
: 定義滾動是立即的還是平滑的動畫
smooth:滾動應該是平滑的動畫。
instant:滾動應該通過一次跳躍立刻發生。
auto:滾動行為由 scroll-behavior 的計算值決定
block
: 定義垂直方向的對齊
可選值:start、center、end 或 nearest ,默認為 start。
inline
: 定義水平方向的對齊
可選值: start、center、end 或 nearest 。默認為 nearest。
3. 示例代碼
<!-- 通過操作dom節點上的 scrollIntoView方法來實現將元素滾到可視區-->
<template><div class="outer"><div class="tab-outer-wrap"><div class="tab-wrap"><div class="tab-item" :class="{ 'active-tab': index === activeIndex }" v-for="(item, index) in tabs":key="index" @click="changeTab(index)">{{ item }}</div></div></div><div class="content-wrap"><div class="content-item" v-for="(item, i) in tabs" :key="i" :ref="(e: any) => (contentRefs[i] = e)">{{ item }}</div></div></div>
</template>
<script setup lang="ts">
// contentRefs 是一個對象,存儲多個ref,鍵名是索引,值是dom實例
const contentRefs = reactive<Record<number, HTMLDivElement>>({});const tabs = ['A', 'B', 'C', 'D', 'E']
const activeIndex = ref(0)
const changeTab = (index: number) => {activeIndex.value = index// 將當前激活的tab對應的content滾動到可視區域contentRefs[index].scrollIntoView({behavior: 'smooth',//定義滾動是立即的還是平滑的動畫block: 'start',//定義垂直方向的對齊inline: 'nearest'//定義水平方向的對齊})
}</script>
<style scoped lang="scss">
.outer {position: relative;width: 100%;height: 100%;
}.tab-outer-wrap {position: fixed;top: 0;left: 0;width: 100%;z-index: 999;
}.tab-wrap {display: grid;grid-template-columns: repeat(5, 1fr);height: 40px;.tab-item {display: flex;justify-content: center;align-items: center;background-color: rgb(235, 231, 226);&.active-tab {color: red;}}
}.content-wrap {position: absolute;top: 40px;left: 0;width: 100%;height: 100%;.content-item {height: 220px;background-color: rgb(238, 219, 195);margin-bottom: 10px;// 定義滾動吸附區域的上外邊距scroll-margin-top: 40px;display: flex;justify-content: center;align-items: center;}
}
</style>