微信小程序实现漂亮的弹窗效果

https://www.10qianwan.com/articledetail/202600.html
转自:
最近项目里需要实现一个带着logo的美美哒弹窗,可是翻遍小程序的文档也只能见到wx.showmodal这个丑丑的东西…… 场面一度十分尴尬 可是得做啊,要不然产品大

最近项目里需要实现一个带着logo的美美哒弹窗,可是翻遍小程序的文档也只能见到wx.showmodal这个丑丑的东西……
场面一度十分尴尬
可是得做啊,要不然产品大姐又要暴走了……
好吧,来研究一下模态对话框的性质自己diy吧~

实现思路

模态对话框之所以被叫做“模态”,就是因为在它弹出的时候,用户如果不关闭这个对话框,是无法对其他窗口进行操作的。
那么这样一来,我们的思路就很明确了:

1. 构建一个蒙层(mask),使得背景变暗,并且阻止用户对对话框外界面的这里写代码片点击事件;
2. 构建一个对话框,在需要时弹出即可(弹出同时触发蒙层)。

示例代码

.wxml:

1
2
3
4
5
6
7
8
9
<view class="mask" catchtouchmove="preventtouchmove" wx:if="{{showmodal}}"></view>
 
<view class="modaldlg" wx:if="{{showmodal}}">
  <image src="/figures/logo-smile.png"/>
  <text>欢迎来到模态对话框~</text>
  <button bindtap="go">点我可以关掉对话框</button>
</view>
 
<button bindtap="submit">点我弹窗</button>

.wxss:

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
.mask{
  width: 100%;
  height: 100%;
  position: fixed;
  top: 0;
  left: 0;
  background: #000;
  z-index: 9000;
  opacity: 0.7;
}
 
.modaldlg{
  width: 580rpx;
  height: 620rpx;
  position: fixed;
  top: 50%;
  left: 0;
  z-index: 9999;
  margin: -370rpx 85rpx;
  background-color: #fff;
  border-radius: 36rpx;
  display: flex;
  flex-direction: column;
  align-items: center;
}

.js:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
page({
 
  data: {
    showmodal: false
  },
 
  submit: function() {
    this.setdata({
    showmodal: true
    })
  },
 
  preventtouchmove: function() {
 
  },
 
 
  go: function() {
    this.setdata({
    showmodal: false
    })
  }
 
})

需要注意的地方

  1. 蒙层view中绑定的preventtouchmove函数是一个空函数,使用了catch事件,目的就是阻止touchmove这样一个冒泡事件继续向下传递。
  2. 蒙层的wxss样式中,指定其大小为100%以占满整个屏幕。
  3. 模态对话框与蒙层的wxss样式中均有z-index属性,为的是保证对话框始终浮在蒙层的上方(即对话框的z-index始终要比蒙层的大)
posted @ 2022-06-11 19:03  长白山  阅读(640)  评论(0编辑  收藏  举报