1. 程式人生 > >微信小程序之自定義toast彈窗

微信小程序之自定義toast彈窗

pla cnblogs display pan false 返回 頁面 文件 src

微信小程序裏面的自帶彈窗icon只有兩種,success和loading。有時候用戶輸入錯誤的時候想加入一個提醒圖標,也可以使用wx.showToast中的image來添加圖片達到使用自定義圖標的目的;但是如果圖標是字體,或者提醒的內容有很長捏(小程序中提醒的內容最多只能設置7個字,多了會被隱藏),那就只有自定義toast彈窗了;

第一步:新建一個wxml文件用來裝模板,方便以後使用,比如

技術分享圖片

然後在這裏面添加模板代碼

<template name="toast">        //name相當於模板的標識,引用的時候好判斷引用哪一個
     <view class
=‘toast-out‘ wx:if=‘{{isShow}}‘>    //wx:if是條件渲染,使用這個是為了好判斷是否顯示或隱藏toast <view class=‘toast-in‘>       <span class=‘iconfont {{iconClass}}‘></span> //使用的阿裏字體圖標,根據傳入的class值改變顯示的圖標 <view class=‘toast-txt‘> {{txt}}          //需要顯示的提醒內容
</view> </view> </view> </template>

第二步:定義toast的樣式

.toast-out {
  position: fixed;
  top: 0;
  left: 0;
  z-index: 9999;
  width: 100%;
  height: 100%;
  display: flex;             //小程序中多使用flex布局,很方便的
  justify-content: center;  
  align-items: center;
}
.toast-out .toast-in 
{ min-width: 100px; background: rgba(0, 0, 0, 0.7); padding: 6px; text-align: center; color: white; border-radius: 8px; } .toast-out .toast-in span { font-size: 30px; } .toast-out .toast-in .toast-txt { font-size: 14px; }

第三步:在需要彈窗的頁面import那個toast模板頁面

<import src="../../public/html/template.wxml" />

    備註:../是指返回上一層目錄即父目錄,兩個../即返回到父目錄的父目錄。/是根目錄,絕對路徑。這裏也可以使用絕對路徑

    然後再在這個頁面任何地方引用模板

<template is="toast" data="{{txt,isShow,iconClass}}"></template>

第四步:在引入彈窗頁面的js中

    在page的data裏先定義 isShow:false //默認隱藏的 但是我有點奇怪的是,不定義這個屬性,註釋掉,都能正常的隱藏與顯示。

    然後定義一個顯示彈窗的函數

toastShow:function(str,icon){
    var _this = this;
    _this.setData({
        isShow: true,
        txt: str,
        iconClass:icon
    });
    setTimeout(function () {    //toast消失
        _this.setData({
            isShow: false
        });
    }, 1500);  
}

    然後在需要toast彈窗顯示的事件裏調用該事件就行了,比如:

log_btn:function(){
    var name=this.data.userName;if(name==""){
        this.toastShow(‘登錄名不能為空‘,"icon-suo");
    }
}

結果:

技術分享圖片圖標隨意弄的。。。

連接:小程序使用阿裏字體圖標

總結: 和HTML不一樣,小程序中wx:if條件渲染就可以實現隱藏與顯示的wx:if="false"就是隱藏,true就是顯示。

   使用display:flex彈性盒子布局很方便,就比如上面彈窗的水平與垂直居中,只要設置兩個屬性就可以了。不用再像以前一樣還需要設置其它的一堆,以前水平垂直居中的方法

補充:

  justify-content 的可選屬性有:flex-start(全靠左),flex-end(全靠右),center(居中),space-between,space-around,initial(從父元素繼承該屬性)

  可查看效果:http://www.runoob.com/try/playit.php?f=playcss_justify-content&preval=flex-start

  align-items 的可選屬性有:stretch,center,flex-start,flex-end,baseline(處於同一條基線),initial(設置為默認值),inherit(從父元素繼承該屬性)

  可查看效果:http://www.runoob.com/try/playit.php?f=playcss_align-items&preval=baseline

微信小程序之自定義toast彈窗