滑倒指定位置:获取指定的dom,然后用scrollIntoView使dom出现在视图区域
回到顶部:操作父级dom的scrollTop = 0,让该父级下的列表回到顶部
代码如下
<template><div class="testDemo"><div><el-button @click="toItem('id50')">滑到指定位置</el-button><el-button @click="toTop">回到顶部</el-button></div><div class="box"><divv-for="(item, index) in 99":key="index":id="'id' + item"class="box_item">{{ item }}</div></div></div>
</template><script>
export default {data() {return {};},methods: {// 滑到指定位置toItem(id) {this.$nextTick(() => {const node = document.getElementById(id); // 通过Id获取到对应的dom元素setTimeout(() => {if (node) {this.$nextTick(() => {node.scrollIntoView({behavior: "smooth", //顺滑的滚动block: "center", //容器上下的中间 start:顶部 end:底部 center:垂直方向居中inline: "start", //容器左右的左边}); // 通过scrollIntoView方法将对应的dom元素定位到可见区域 【block: 'center'】这个属性是在垂直方向居中显示});}}, 100);});},// 回到顶部toTop() {// 第一种方式// var et = document.getElementsByClassName("box");// if (et && et.length) {// et[0].scrollTop = 0;// }// 第二种方式 较为平滑this.$nextTick(() => {const node = document.getElementById("id1");setTimeout(() => {if (node) {this.$nextTick(() => {node.scrollIntoView({behavior: "smooth",block: "start",inline: "start",});});}}, 100);});},},
};
</script>
<style lang="scss" scoped>
.testDemo {display: flex;flex-direction: column;.box {flex-grow: 1;border: 1px solid #000;overflow: auto;.box_item {height: 50px;border: 1px solid #000;}}
}
</style>