Element.scrollIntoView() 方法讓當前的元素滾動到瀏覽器窗口的可視區域內。
語法:
element.scrollIntoView(); // 等同於element.scrollIntoView(true) element.scrollIntoView(alignToTop); // Boolean型參數 element.scrollIntoView(scrollIntoViewOptions); // Object型參數
參數:
alignToTop (可選): 一個Boolean值;
- 如果為
true,元素的頂端將和其所在滾動區的可視區域的頂端對齊。相應的scrollIntoViewOptions: {block: "start", inline: "nearest"}。這是這個參數的默認值。 - 如果為
false,元素的底端將和其所在滾動區的可視區域的底端對齊。相應的scrollIntoViewOptions: {block: "end", inline: "nearest"}。
scrollIntoViewOptions (可選):一個包含下列屬性的對象;
behavior(可選)定義動畫過渡效果,"auto"或"smooth"之一。默認為"auto"。block(可選)定義垂直方向的對齊,"start","center","end", 或"nearest"之一。默認為"start"。inline(可選)定義水平方向的對齊,"start","center","end", 或"nearest"之一。默認為"nearest"。
示例:
var element = document.getElementById("box"); element.scrollIntoView(); element.scrollIntoView(false); element.scrollIntoView({block: "end"}); element.scrollIntoView({behavior: "instant", block: "end", inline: "nearest"});
在vue中使用: 需求,一個滾動列表,根據某個條件要找到其中一列並顯示在可視區域中
<template>
<div class="list-wrap">
<ul>
<li v-for="(item,index) in 100" :key="index" :ref="`li${index+1}`"></li>
</ul>
</div>
</template>
<script>
export default {
data() {
return {}
},
mounted() {
let _index = 10;
this.$nextTick(() => {
this.$refs[`li${_index + 1}`].scrollIntoView(); //定位到第幾條的滾動位置
})
}
}
</script>
瀏覽器兼容性:

