Vue实现滚动到具体某元素位置


document.getElementById('ID').scrollIntoView()

scrollIntoView()有三个参数:


scrollIntoView({ behavior:"smooth", block: "start", inline: "start"})

  1. behavior 表示滚动方式。auto 表示使用当前元素的 scroll-behavior 样式。instant 和 smooth

    表示 直接滚到底 和 使用平滑滚动。

  2. block 表示块级元素排列方向要滚动到的位置。对于默认的 writing-mode: horizontal-tb

    来说,就是竖直方向。start 表示将视口的顶部和元素顶部对齐;center

    表示将视口的中间和元素的中间对齐;end表示将视口的底部和元素底部对齐;nearest 表示就近对齐。

  3. 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>

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容