程序员求职经验分享与学习资料整理平台

网站首页 > 文章精选 正文

vue3实现一个无缝衔接、滚动平滑的列表自动横滚屏效果

balukai 2025-01-11 10:25:03 文章精选 9 ℃


<template>
  <div class="warning-view">
    <div class="scroll-view" ref="scrollViewRef">
      <div ref="listRef" class="list" v-for="(p, n) in 2" :key="n">
        <div class="item" v-for="(item, index) in data" :key="index">
          <div class="content">第{{ index + 1 }}次AI标准工作会议通知</div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onBeforeMount, onMounted, onBeforeUnmount, nextTick } from "vue";
const data = ref(); //列表数据
const listRef = ref(); //列表dom
const scrollViewRef = ref(); //滚动区域dom

let intervalId = null;

//获取列表数据
const getData = () => {
  //模拟接口请求列表数据
  return new Promise((resolve, reject) => {
    setTimeout(() => {
      //生成10条数据
      let list = new Array(6).fill().map((item, index) => index);
      resolve(list);
    }, 1000);
  });
};

onMounted(async () => {
  data.value = await getData();
  nextTick(() => {
    autoScrolling();
  });
});
//设置自动滚动
const autoScrolling = () => {
  intervalId = setInterval(() => {
    if (scrollViewRef.value.scrollLeft < listRef.value[0].clientWidth) {
      scrollViewRef.value.scrollLeft += 1;
    } else {
      scrollViewRef.value.scrollLeft = 0;
    }
  }, 20);
};

onBeforeUnmount(() => {
  //离开页面清理定时器
  intervalId && clearInterval(intervalId);
});
</script>

<style scoped>
.warning-view {
  width: 100%;
  height: 50px;
  border-radius: 5px;
  background: #f1f1f1;
  box-shadow: 0px 0px 19px 2px rgba(0, 51, 102, 0.29);
  background-image: url("@/assets/images/color-bg.png");
  background-repeat: no-repeat;
  background-size: cover;
  display: flex;
  margin-bottom: 40px;
}
.scroll-view {
  height: 50px;
  width: 100%;
  overflow-x: auto;
  display: flex;
}
.list {
  width: auto;
  display: flex;
  white-space: nowrap;
  box-sizing: border-box;
}
.item {
  width: auto;
  height: 50px;
  font-size: 16px;
  margin-right: 30px;
  display: flex;
  align-items: center;
  justify-content: space-between;
}
/**
  *隐藏滚动条
   */
::-webkit-scrollbar {
  display: none;
}
</style>

Tags:

最近发表
标签列表