微信小程序带图片弹窗简单实现
2020-09-27|HiShop
导读:怎样实现一个带图片显示的模态视图弹窗呢?有时候我们的确有这个需求,自下面我来介绍一种使用官方组件就能实现的方法: ...
怎样实现一个带图片显示的模态视图弹窗呢?有时候我们的确有这个需求,自己实现?不不不,哪有官方的方便!
下面我来介绍一种使用官方组件就能实现的方法:
首先找到官方文档:显示模态弹窗的API wx.showModal(OBJECT)
wx.showModal参数介绍
发现并没有设置图片的参数,但是这是一个API,但是组件呢?我并没有在官方文档中找到,但是经过尝试发现是可以显示一个模态弹窗的,即:
- wx.showModal({
- title: '提示',
- content: '这是一个模态弹窗',
- success: function(res) {
- if (res.confirm) {
- console.log('用户点击确定')
- } else if (res.cancel) {
- console.log('用户点击取消')
- }
- }
- })
可以改写为:
- <modal title='提示' hidden="{{modalHidden}}" bindcancel='modalCancel' bindConfirm='modalConfirm'>
- 这是一个模态弹窗
- </modal>
但是是否隐藏,确认以及取消的回调都需要自己手动绑定至js进行控制,效果还是一样的
普通模态弹窗 下面我们给他加上图片:
//wxml: 代码如下
- <view class='container'>
- <button class='button' bindtap='buttonTap' type='primary'>显示弹窗</button>
- <modal title="我是标题" hidden="{{modalHidden}}" bindconfirm="modalConfirm" bindcancel="modalCandel">
- <view>
- <image class="image" src="../images/image.jpg" mode='aspectFill'></image>
- </view>
- //需要换行的话直接添加view标签
- <view>You say that you love rain,</view>
- <view>but you open your umbrella when it rains...</view>
- You say that you love the sun,
- but you find a shadow spot when the sun shines...
- You say that you love the wind,
- But you close your windows when wind blows...
- This is why I am afraid; You say that you love me too...
- </modal>
- </view>
//js: 代码如下
- Page({
- /**
- * 页面的初始数据
- */
- data: {
- modalHidden: true
- },
- /**
- * 显示弹窗
- */
- buttonTap: function() {
- this.setData({
- modalHidden: false
- })
- },
- /**
- * 点击取消
- */
- modalCandel: function() {
- // do something
- this.setData({
- modalHidden: true
- })
- },
- /**
- * 点击确认
- */
- modalConfirm: function() {
- // do something
- this.setData({
- modalHidden: true
- })
- }
- })
带图片模态弹窗 我们还可以定制图片大小:
wxss: 代码
- .image {
- width: 150rpx;
- height: 120rpx;
- margin: 10rpx 20rpx 0rpx 0rpx;
- float: left;
- }
这样子的话其实大家就明白了,只是一个容器,大家可以尽情的发挥想象去定制,既不用完全自己去实现一个自定义模态弹窗视图,又可以摆脱官方wx.showModal的简陋