uniapp + vue 定位聊天最新消息 實現滾動條一直在元素的最底部

使用 scroll-view 配合uni.createSelectorQuery() 以及boundingClientRect()即可實現;

<scroll-view id="scrollview" class="chat-window" scroll-y="true" :style="{height: style.contentViewHeight + 'px'}"
		 :scroll-with-animation="true" :scroll-top="scrollTop">
		<view class="content-all">
				<block v-for="(item,index) in messages" :key="index" class="m-item">
					<view class="user-chat-item animated fadeIn fast u-f right" v-if="globalUser.id==item.fromUserId">
						<view class="meet-name fb">{{item.msg}}:{{globalUser.name}}</view>
					</view>
					<view class="user-chat-item animated fadeIn fast u-f left" v-else>
						<view class="meet-name fb">{{name}}:{{item.msg}}</view>
					</view>

				</block>
		</view>
		<view id='gundong' style='height:1px;width:100%'></view>

</scroll-view>


使用生命週期函數

        mounted() {
			uni.createSelectorQuery().select("#gundong").boundingClientRect((res) => {
				this.oldbottom = res.bottom // 記錄 滾動 元素的 bottom 值
				console.log(this.oldbottom)
			}).exec();
		},
		updated() {
			setTimeout(() => {
				uni.createSelectorQuery().select("#gundong").boundingClientRect((res) => {
					console.log(res)
					var newbottom = res.bottom
					if (Number(newbottom) > Number(this.oldbottom)) {
						this.scrollTop = newbottom
					}
					this.oldbottom = newbottom
					console.log(this.oldbottom)
				}).exec();
			}, 400)

		},

		created() {
			const res = uni.getSystemInfoSync(); //獲取手機可使用窗口高度     api爲獲取系統信息同步接口
			this.style.pageHeight = res.windowHeight;
			this.style.contentViewHeight = res.windowHeight - uni.getSystemInfoSync().screenWidth / 750 * (30) - 60; //像素   因爲給出的是像素高度 然後我們用的是upx  所以換算一下 
			this.scrollToBottom(); //創建後調用回到底部方法
		},

一定要加 setTimeout(() => {},400 ) 這樣消息纔會最下面 

好像是讓頁面全部加載完畢之後  只能自己通過 定時 達到異步的效果

看了好多博客 總是差一點  最後結合了 好幾篇的結果

 

樣式的話 自己寫下吧  我用了全局樣式  

<style>
	.left {
		flex-direction: row;
	}

	.right {
		flex-direction: row-reverse;
	}

	.meet-name {
		padding: 10upx 20upx;
		font-size: 28upx;
		/* margin-bottom: 20upx; */
	}

	.login-bottom {
		position: fixed;
		bottom: 0;
	}

	.login-bottom-input {
		display: flex;
		justify-content: space-between;
	}

	.login-bottom-input>input {
		background: #F7F9FF;
		border-radius: 28upx;
		width: 568upx;
		height: 62upx;
		margin: 30upx;
		color: #999999;
		font-size: 13px;
		padding-left: 20upx;
	}

	.login-bottom-input>text {
		color: #2774CB;
		font-size: 18px;
		height: 80upx;
		line-height: 80upx;
		padding-right: 20upx;
		padding-top: 20upx;
		font-weight: bold;

	}

	.demoList {
		text-align: center;
		line-height: 100upx;
	}

	
</style>

 

發佈了73 篇原創文章 · 獲贊 27 · 訪問量 5萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章