Vue結合uniapp實現水平公告欄

開發路上的AZhe發表於2020-12-21

參考文件:https://blog.csdn.net/jjw_zyfx/article/details/102225767

<view class="announcement">
				<view class="ziti">
					鮮果快報:
				</view>
				<view class="gonggao">
					<view style="color: #FFC944;">每日 | </view>
					<view class="outer-box">
						<view class="inner-box1"  :style="{'position': 'relative','right':scrollLeft+'px'}">
							<view v-for="(item,index) in noticeList" :key="index">
								{{item}}
							</view>
						</view>
						<!--注意inner-box1和inner-box2的資料必須一樣,並且樣式也得一樣
					  inner-box2包裹的頂部要注意和inner-box1的底部的距離應和其包裹的
					  每兩個div之間的距離一樣否則會出現卡頓的效果-->
						<view class="inner-box2" :style="{'position': 'relative','right':scrollLeft+'px'}">						
								<view v-for="(item,index) in noticeList" :key="index">
									{{item}}
								</view>
						</view>
					</view>
				</view>
			</view>

#js部分
export default {
		data() {
			return {
				noticeList: ['每日一條公告', '每日二條公告', '每日san條公告'],
				scrollLeft:0
			}
		},
		onReady() {
			console.log('渲染成功!!!');
			let outerBox;
			let innerBox;
			uni.createSelectorQuery().selectAll(".outer-box").scrollOffset(res=>{
				outerBox= res["0"];
			}).exec();
			uni.createSelectorQuery().selectAll(".inner-box1").boundingClientRect(res=>{
				innerBox= res["0"];
			}).exec();
			setInterval(() => {
				this.scrollFunc(outerBox, innerBox)
			}, 30)
		},
		methods: {
			scrollFunc(outerBox, innerBox) {
				if (outerBox.scrollLeft >= innerBox.width) {
					outerBox.scrollLeft = 0;
				} else {
					outerBox.scrollLeft ++;
				}
				this.scrollLeft = outerBox.scrollLeft;
			}
		}
	}
#css部分
.announcement {
		display: flex;
		justify-content: flex-start;
		align-items: center;
		width: 100%;
		margin: 0 auto;
		font-size: 20rpx;
	}

	.gonggao {
		border-radius: 45rpx;
		background-color: #FAFAFA;
		width: 70%;
		padding: 6rpx 20rpx;
		font-size: 15rpx;
		margin-left: 20rpx;
		display: flex;
		justify-content: flex-start;
		align-items: center;
	}

	.outer-box {
		text-align: center;
		width: 80%;
		margin: 0 auto;
		overflow: hidden;
		/* 這個屬性很重要一定要設定*/
		display: flex;
		flex-flow: row nowrap;
	}

	.inner-box1,
	.inner-box2 {
		display: flex;
		flex-flow: row nowrap;
		white-space: nowrap;
	}

	.inner-box1 view,
	.inner-box2 view {
		margin-right: 20px;
	}

相關文章