VUE移动到指定位置(scrollIntoView)

132 阅读1分钟
<template>
	<div id="app">
	<!-- 轮播 -->
	<div class="planting">
    <el-carousel ref="slide" indicator-position="outside" class="slideBox">
      <el-carousel-item  v-for="(item, index) in items" :key="index" >
        <img @click="imgus('aa'+index)" :src="item.image">
      </el-carousel-item>
    </el-carousel>
	</div>
	<!-- 轮播 -->
	<img style="width: 100%;float: left;" v-for="(item,index) in items" :id="'aa'+index" :src="item.image" :key="'aa'+index">
	</div>
</template>

<script>
export default {
  props: {
    msg: String
  },
  data() {
    return {
		items: [
		{
		  url: '',
		  image: 'https://img0.baidu.com/it/u=2463124937,763497726&fm=253&app=138&size=w931&n=0&f=JPEG&fmt=auto?sec=1738947600&t=2b5a39feda911b4e7ec693cb73cc6157'
		},
		{
		  url: '',
		  image: 'https://img0.baidu.com/it/u=2336706355,1827042531&fm=253&app=138&size=w931&n=0&f=JPEG&fmt=auto?sec=1738947600&t=493f02e89086d7fbf48a62495f6eca13'
		},
		{
		  url: '',
		  image: 'https://img1.baidu.com/it/u=2381757946,987933602&fm=253&app=138&size=w931&n=0&f=JPEG&fmt=auto?sec=1738947600&t=a33c995ee315e1307118435f950f35db'
		}
		],
    }
  },
  mounted(){
  },
  methods: {
	  //滚动指定位置
	  imgus:function(e){
	  	document.getElementById(e).scrollIntoView({
	  	  behavior: "smooth",  // 平滑过渡
	  	  block:    "start"  // 上边框与视窗顶部平齐。默认值
	  	});
	  }
   },
}
</script>
<style>
	.slideBox img{
		width: 100%;
		height: 100%;
	}
	.planting{
		width: 100%;
		height: 20rem;
		overflow: hidden;
	}

</style>

html

<div id="pronbit" ref="pronbit">需要移动到的位置</div>

js

//选中id
document.getElementById(e).scrollIntoView({
	behavior: "smooth",  // 平滑过渡
	block:    "start"  // 上边框与视窗顶部平齐。默认值
});
// 选中ref
this.$refs.pronbit.scrollIntoView({
	behavior: "smooth",  // 平滑过渡
	block:    "start"  // 上边框与视窗顶部平齐。默认值
});



//要是放在mounted()里执行使用
this.$refs.pronbit.scrollIntoView();//不然只执行一次刷新了也一样

//禁止scrollIntoView
this.$refs.pronbit.scrollIntoView(false);

参考网友方法记录一下