由于微信小程序必须用按钮才能触发分享事件。
当我们需要点击图片来触发时,这个按钮就显得捉襟见肘了。
先展示一下完成效果
这里是用uni App 写的,其样式使用了 TailWind Css
[TailWind 官方文档] www.tailwindcss.cn/
实现的代码
<view class="flex w-full p-6">
<view class="flex flex-col items-center relative">
<button class="absolute top-0 left-0" type="default" open-type="share" style="width: 150rpx;height: 150rpx;opacity: 0;" />
<u-image style="z-index: -1;" width="100" src="/static/recommend/Wechat.png" mode="widthFix"></u-image>
<text style="font-weight: normal;font-size: 24rpx;" class="px-2">微信分享</text>
</view>
<view class="flex flex-col text-center ml-4 relative items-center">
<button class="absolute top-0 left-0" type="default" open-type="share" style="width: 150rpx;height: 150rpx;opacity: 0;" />
<u-image style="z-index: -1;" width="100" src="/static/recommend/WechatMoments.png" mode="widthFix"></u-image>
<text style="font-weight: normal;font-size: 24rpx;" class="px-2">生成海报</text>
</view>
</view>
我们可以发现 小程序中的Button组件自带了一些样式 并且一些样式是写在 伪元素上面的 我们可以在Style标签中去掉
<style scoped="less">
button::after {
height: 0;
padding: 0;
border: none;
background-color: white;
}
</style>
实现思路:
1. 通过绝对定位使原来的Button元素脱离文档流 并将其的宽高设定为要显示的图片大小以确保点击图片是在Button的范围内的
2. 这个时候通过设置opacity 属性为 0 (设置为完全透明) 来隐藏这个元素
3. 这个时候我们发现点击图片还是无法触发点击事件
4. 将图片的层级下降一级 以确保点击到的是Button区域就可以解决 上面的问题