uniapp无缝滚动核心代码
1、页面代码核心代码
<scroll-view class="scoll-warp"> <view id="scoll-wrapper" class="scoll-wrapper" :animation="animation.animationData"> <view v-for="(item, index) in listData" :key="index" class="floor-item gaokong-item"> <image :src="item.thumb" mode="aspectFill"></image> <text class="title clamp">{{ item.name }}</text> </view> </view> </scroll-view>
2、css核心样式
.scoll-warp { white-space: nowrap; } .scoll-wrapper { display: flex; align-items: flex-start; } .floor-item { width: 150upx; margin-right: 20upx; font-size: 26upx; color: #333; line-height: 1.8; image { width: 150upx; height: 150upx; border-radius: 6upx; } }
3、系统变量
data() { return { listData: [], //数据 animation: { scrollWidth: 0, width: 0, itemWidth: 0, animationData: {} } }; }
4、动画核心
readyScroll() { let that = this, query = uni.createSelectorQuery().in(this); this.$nextTick(function() { //不加延时,取得不到数据 setTimeout(function() { query .selectAll('.gaokong-item') .boundingClientRect(res => { if (res.length > 0) { //宽度减去屏幕宽度that.systmInfo.windowWidth,that.systmInfo.windowWidth需要实际计算 that.animation.width = res[0].right * res.length - that.systmInfo.windowWidth; that.animation.itemWidth = res[0].right; console.log(that.animation); if (that.animation.width > 10) { that.doScroll(); } } }) .exec(); }); }, 500); }, doScroll() { let that = this, speed = 3000; let animation = uni.createAnimation({ timingFunction: 'linear', delay: 0 }); let width = 0 - that.animation.width; setInterval(() => { if (that.animation.scrollWidth <= width) { animation.translateX(0).step(); that.animation.scrollWidth = 0; that.animation.animationData = animation.export(); } else { that.animation.scrollWidth = that.animation.scrollWidth - that.animation.itemWidth; animation.translateX(that.animation.scrollWidth).step(); that.animation.animationData = animation.export(); } }, speed); }
5、调用
onReady() { this.readyScroll(); }