document.getElementById('ID').scrollIntoView()
scrollIntoView()有三个参数:
scrollIntoView({ behavior:"smooth", block: "start", inline: "start"})
-
behavior 表示滚动方式。auto 表示使用当前元素的 scroll-behavior 样式。instant 和 smooth
表示 直接滚到底 和 使用平滑滚动。
-
block 表示块级元素排列方向要滚动到的位置。对于默认的 writing-mode: horizontal-tb
来说,就是竖直方向。start 表示将视口的顶部和元素顶部对齐;center
表示将视口的中间和元素的中间对齐;end表示将视口的底部和元素底部对齐;nearest 表示就近对齐。
-
inline 表示行内元素排列方向要滚动到的位置。对于默认的 writing-mode: horizontal-tb
来说,就是水平方向。其值与 block 类似
{
behavior: "auto" | "instant" | "smooth", // 默认 auto
block: "start" | "center" | "end" | "nearest", // 默认 center
inline: "start" | "center" | "end" | "nearest", // 默认 nearest
}
案例:
vue 单文件运行 vue serve + 文件名
<template>
<div class="content">
<div class="demo" :id="index" v-for="(item, index) in params" :key="index">
<span>{{item.name}}</span>
<button class="btn" :class="index===0?'isShow':''" @click="handle(index)">上一步</button>
</div>
</div>
</template>
<script>
export default {
data () {
return {
params: [
{ id: 1, name: '楸1' },
{ id: 2, name: '楸2' },
{ id: 3, name: '楸3' },
{ id: 4, name: '楸4' },
{ id: 5, name: '楸5' },
{ id: 6, name: '楸6' },
{ id: 7, name: '楸7' },
{ id: 8, name: '楸8' },
{ id: 9, name: '楸9' },
{ id: 10, name: '楸10' },
{ id: 11, name: '楸11' },
{ id: 12, name: '楸12' },
{ id: 13, name: '楸13' },
]
}
},
components: {
},
computed: {
},
watch: {
},
methods: {
handle (index) {
let i = index - 1
document.getElementById(i).scrollIntoView({ behavior: 'smooth' })
}
},
created () {
},
mounted () {
}
}
</script>
<style lang='less' scoped>
.demo {
position: relative;
width: 100%;
height: 300px;
border: 1px solid rgb(0, 158, 163);
margin: 50px;
}
.btn {
position: absolute;
bottom: 0;
left: 0;
}
.isShow {
display: none;
}
</style>