uniapp 实现上下一条一条滚动内容 - 详细教程和示例代码
<p>在 uniapp 中,可以使用`setInterval`函数来实现上下一条一条滚动的效果。</p>
<p>首先,在`<template>`中,需要使用`<scroll-view>`组件来实现滚动。可以设置`scroll-y`属性为`true`来启用垂直滚动,并设置`scroll-with-animation`属性为`true`以启用滚动动画。同时,需要在`<scroll-view>`中添加一个`<view>`作为滚动内容的容器。</p>
<p>接下来,在`<script>`中,可以使用`data`来存储滚动内容的数组和当前显示的内容的下标。然后,在`onLoad`生命周期函数中,可以使用`setInterval`函数来定时更新当前显示的内容的下标,并通过`<scroll-view>`的`scroll-top`属性来设置滚动位置。</p>
<p>以下是一个简单的示例代码:</p>
<pre><code><template>
<scroll-view class="scroll-view" scroll-y scroll-with-animation>
<view class="content">
{{ content[currentIndex] }}
</view>
</scroll-view>
</template>
<script>
export default {
data() {
return {
content: [
'第一条内容',
'第二条内容',
'第三条内容',
'第四条内容',
],
currentIndex: 0,
}
},
onLoad() {
setInterval(() => {
const nextIndex = this.currentIndex === this.content.length - 1 ? 0 : this.currentIndex + 1
this.currentIndex = nextIndex
uni.pageScrollTo({
scrollTop: nextIndex * 50, // 每条内容高度为50px
duration: 500, // 滚动动画时间为500ms
})
}, 2000) // 每2秒切换一次内容
}
}
</script>
<style>
.scroll-view {
height: 200px;
}
.content {
height: 50px;
line-height: 50px;
text-align: center;
}
</style>
</code></pre>
<p>需要注意的是,上述示例中假设每条内容的高度为50px,因此在设置滚动位置时需要乘以50。实际情况中需要根据实际内容高度进行调整。</p>
原文地址: https://www.cveoy.top/t/topic/m9n5 著作权归作者所有。请勿转载和采集!