微信小程序WebView上的悬浮组件实现
在微信小程序开发中,经常会遇到需要加载H5页面的场景,特别是需要展示公众号文章内容时。但由于微信的WebView组件的限制,实现在WebView上方显示任何原生组件都是不允许的。本文将分享如何在小程序WebView上实现悬浮点赞、评论等交互组件的解决方案。
问题背景
在我的小程序项目中,需要展示大量公众号文章。然而,我们希望用户在跳转阅读公众号文章的同时,能够使用小程序自带的点赞、评论等功能,而不必打开退出公众号文章去进行。这就要求在WebView上方叠加显示悬浮操作按钮。
官方文档指出,web-view是一个特殊的原生组件,默认会覆盖其它所有组件。这意味着普通的小程序组件无法显示在WebView上方。基本使用方式如下:
解决方案
为了实现在WebView上方显示悬浮操作按钮,我们需要使用微信小程序的cover-view和cover-image组件。
使用cover-view覆盖
cover-view和cover-image。我们可以利用这两个组件在WebView上方实现悬浮按钮。
实现代码
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
| <template> <view class="container"> <web-view :src="url"></web-view> <cover-view v-if="showActions" class="float-actions"> <cover-view class="action-btn view"> <cover-image class="icon" src="/static/icons/view.png"></cover-image> <cover-view class="count">{{views || 0}}</cover-view> </cover-view> <cover-view class="action-btn like" @tap="handleLike"> <cover-image class="icon" :src="isLiked ? '/static/icons/liked.png' : '/static/icons/like.png'"></cover-image> <cover-view class="count">{{likes || 0}}</cover-view> </cover-view> <cover-view class="action-btn comment" @tap="handleComment"> <cover-image class="icon" src="/static/icons/comment.png"></cover-image> <cover-view class="count">{{totalComments || 0}}</cover-view> </cover-view> </cover-view> </view> </template>
|
注意:
使用cover-view时,可能pc测试时看不到效果,需要真机测试,而且部分机型可能存在问题
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32
| .float-actions { position: fixed; right: 20rpx; bottom: 40rpx; z-index: 999999; display: flex; flex-direction: row; align-items: center; }
.action-btn { width: 80rpx; height: 80rpx; margin-left: 20rpx; background: rgba(0, 0, 0, 0.6); border-radius: 50%; display: flex; flex-direction: column; align-items: center; justify-content: center; }
.icon { width: 40rpx; height: 40rpx; margin-bottom: 2rpx; }
.count { color: #fff; font-size: 20rpx; }
|
接下来实现功能逻辑就行 就不进行演示了
总结
通过使用cover-view和cover-image组件,在WebView上方实现悬浮操作按钮, 但是并不确定此方法是微信官方所支持的(或许能在网站上插广告?) ,同时此方法在pc上测试时看不到效果,需要真机测试,而且部分机型可能存在问题