WeChat Mini Program - Realize a simple pop-up layer

         When making a small program project, I want to make a pop-up box with a mask layer, but it is too troublesome to write a component for this one, so I simply write one by hand.

Implementation ideas

The reason why the modal dialog box is called "modal" is because when it pops up, if the user does not close the dialog box, he cannot operate other windows. 
In this way, our thinking is very clear: 
1. Build a mask to darken the background and prevent the user from 这里写代码片clicking on the outside interface of the dialog box; 
2. Build a dialog box, when needed Just pop it out (the pop-up triggers the mask at the same time).

3. Use wx:if to achieve

sample code

.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>

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

.js:

Page({
 
    data: {
        showModal: false
    },
 
    submit: function() {
        this.setData({
        showModal: true
        })
    },
 
    preventTouchMove: function() {
 
    },
 
 
    go: function() { 
        this.setData({
        showModal: false
        })
    }
 
})

need attention

  1. The preventTouchMove function bound in the mask view is an empty function, which uses the catch event to prevent a bubbling event such as touchmove from continuing to pass down.
  2. In the wxss style of the mask, specify its size as 100% to fill the entire screen.
  3. Both the modal dialog box and the wxss style of the mask layer have a z-index attribute, in order to ensure that the dialog box is always floating above the mask layer (that is, the z-index of the dialog box is always larger than that of the mask layer)

If it is useful to everyone, you can like it and collect it¥¥¥¥

Guess you like

Origin blog.csdn.net/xybhua/article/details/128878839