scroll-view 定位到滚动到的地方-前端-E先生的博客
Java
MySQL
大数据
Python
前端
黑科技
大语言模型
    首页 >> 互联网 >> 前端

scroll-view 定位到滚动到的地方

[导读]:源码<template><scroll-view:scroll-x="true":scroll-into-view="scrollIntoViewId"><blockv-for="(item,index)inlist":key=&qu...

源码

<template>
  <scroll-view
    :scroll-x="true"
    :scroll-into-view="scrollIntoViewId"
  >
    <block v-for="(item, index) in list" :key="index">
      <view :id="'item-' + index">
        <text
          @click="change(index)"
          :style="{
            backgroundColor: internalIsActive === index ? '#ff9500' : '',
            color: internalIsActive === index ? '#fff' : '',
          }">
          {{ item }}
        </text>
      </view>
    </block>
  </scroll-view>
</template>
<script>
export default {
  props: {
    list: {
      type: Array,
      required: true,
      default: () => [],
    },
    isActive: {
      type: Number,
      default: 0,
    },
  },
  data() {
    return {
      internalIsActive: 0,
      scrollIntoViewId: '',
    };
  },
  watch: {
    isActive(newVal) {
      this.internalIsActive = newVal;
      this.scrollIntoViewId = `item-${newVal}`; // 监听 isActive 更新滚动
    },
  },
  methods: {
    change(index) {
      this.internalIsActive = index;
      this.$emit('change', index);
      // 使用 $nextTick 确保 DOM 更新后滚动
      this.$nextTick(() => {
        this.scrollIntoViewId = `item-${index}`;
        console.log(`滚动到: ${this.scrollIntoViewId}`);
      });
    },
  },
};
</script>
<style scoped>
.scrollview-box {
  white-space: nowrap;
  width: 100%;
  padding: 20rpx;
}
.item {
  width: 110rpx;
  height: 40rpx;
  margin-right: 20rpx;
  display: inline-flex;
  flex-direction: column;
  align-items: center;
}
.name {
  font-size: 24rpx;
  color: #333;
  line-height: 42rpx;
  width: 90%;
  border: 1px solid #e5e5e5;
  text-align: center;
  text-overflow: ellipsis;
  white-space: nowrap;
  overflow: hidden;
}
</style>

略微写一下 看一下效果

image.png

image.png

本文来自E先生的博客,如若转载,请注明出处:https://javajz.cn

留言区

联系人:
手   机:
内   容:
验证码:

历史留言

欢迎加Easy的QQ