微信小程序 实现简单弹出层

实现思路

模态对话框之所以被叫做“模态”,就是因为在它弹出的时候,用户如果不关闭这个对话框,是无法对其他窗口进行操作的。 
那么这样一来,我们的思路就很明确了: 
1. 构建一个蒙层(mask),使得背景变暗,并且阻止用户对对话框外界面的这里写代码片点击事件; 
2. 构建一个对话框,在需要时弹出即可(弹出同时触发蒙层)。

示例代码

.wxml:

<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>
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10

.wxss:

.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;
}
  • 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

.js:

Page({

    data: {
        showModal: false
    },

    submit: function() {
        this.setData({
        showModal: true
        })
    },

    preventTouchMove: function() {

    },


    go: function() { 
        this.setData({
        showModal: false
        })
    }

})
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24

需要注意的地方

  1. 蒙层view中绑定的preventTouchMove函数是一个空函数,使用了catch事件,目的就是阻止touchmove这样一个冒泡事件继续向下传递。
  2. 蒙层的wxss样式中,指定其大小为100%以占满整个屏幕。
  3. 模态对话框与蒙层的wxss样式中均有z-index属性,为的是保证对话框始终浮在蒙层的上方(即对话框的z-index始终要比蒙层的大)

猜你喜欢

转载自blog.csdn.net/yelin042/article/details/80881618