可以使用 uni-app 的 scroll-view 组件来实现自动一条一条上下滚动的效果。

1. 在页面中添加一个 scroll-view 组件,设置为垂直方向滚动:

<scroll-view scroll-y='true' class='scroll-view'>
    <!-- 内容区域 -->
</scroll-view>

2. 在组件内部添加需要滚动的内容,可以是一个列表或者一段文字。

3. 使用 setInterval 函数来实现定时滚动。在页面的 onLoad 生命周期函数中,设置一个定时器,每隔一定时间将 scroll-view 组件的 scrollTop 属性加上一定的值,使其向下滚动。当 scrollTop 达到一定的值时,将其重置为 0,重新开始滚动。

onLoad() {
  setInterval(() => {
    const scrollTop = this.data.scrollTop + 20;
    if (scrollTop >= this.data.scrollHeight) {
      this.setData({
        scrollTop: 0
      })
    } else {
      this.setData({
        scrollTop
      })
    }
  }, 2000)
}

4. 在样式中设置 scroll-view 的高度和滚动区域的高度,以及滚动条的样式等。

.scroll-view {
  height: 200px;
  overflow: hidden;
}

.scroll-view::-webkit-scrollbar {
  width: 5px;
}

.scroll-view::-webkit-scrollbar-thumb {
  background-color: #ccc;
  border-radius: 5px;
}

完整示例代码:

<template>
  <view>
    <scroll-view scroll-y='true' class='scroll-view' :scroll-top='scrollTop'>
      <view class='content'>
        <view v-for='(item, index) in list' :key='index' class='item'>{{item}}</view>
      </view>
    </scroll-view>
  </view>
</template>

<script>
export default {
  data() {
    return {
      list: ['条目1', '条目2', '条目3', '条目4', '条目5', '条目6', '条目7', '条目8', '条目9', '条目10'],
      scrollTop: 0,
      scrollHeight: 0
    }
  },
  onLoad() {
    this.$nextTick(() => {
      this.setData({
        scrollHeight: this.$refs.scrollView.boundingClientRect.height
      })
      setInterval(() => {
        const scrollTop = this.data.scrollTop + 20;
        if (scrollTop >= this.data.scrollHeight) {
          this.setData({
            scrollTop: 0
          })
        } else {
          this.setData({
            scrollTop
          })
        }
      }, 2000)
    })
  }
}
</script>

<style>
.scroll-view {
  height: 200px;
  overflow: hidden;
}

.content {
  height: auto;
}

.item {
  height: 50px;
  line-height: 50px;
  border-bottom: 1px solid #ccc;
  text-align: center;
}

.scroll-view::-webkit-scrollbar {
  width: 5px;
}

.scroll-view::-webkit-scrollbar-thumb {
  background-color: #ccc;
  border-radius: 5px;
}
</style>
uniapp 自动上下滚动内容 - 使用 scroll-view 实现

原文地址: https://www.cveoy.top/t/topic/m9pA 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录