微信小程序自定義toast代碼開發實用組件/插件。
小程序交互僅提供這些API
wx.showToast的效果是這樣的,太難看了
現在我們來自己寫個toast
一、我們把樣式寫在app.wxss里,這樣每個地方都可以調用到
- /*toast start*/
- .wxapp-toast-mask{
- opacity: 0;
- width: 100%;
- height: 100%;
- overflow: hidden;
- position: fixed;
- top: 0;
- left: 0;
- z-index: 888;
- }
- .wxapp-toast-content-box {
- display: flex;
- width: 100%;
- height: 100%;
- justify-content: center;
- align-items: center;
- position: fixed;
- z-index: 999;
- }
- .wxapp-toast-content {
- width: 50%;
- padding: 20rpx;
- background: rgba(0, 0, 0, 0.7);
- border-radius: 20rpx;
- }
- .wxapp-toast-content-text {
- height: 100%;
- width: 100%;
- color: #fff;
- font-size: 28rpx;
- text-align: center;
- }
- /*toast end*/
二、JS也是寫在在app.js里:
- //自定義Toast
- showToast: function(text,o,count){
- var _this = o;
- count = parseInt(count) ? parseInt(count) : 3000;
- _this.setData({
- toastText:text,
- isShowToast: true,
- });
- setTimeout(function () {
- _this.setData({
- isShowToast: false
- });
- },count);
- },
三、在需要調用的wxml文件中合適的地方加上下面代碼:(比如index.wxml,注意:有container要放在里面)
- <view class="container">
- <!--wxapp-toast start-->
- <view class="wxapp-toast-content-box" wx:if="{{isShowToast}}">
- <view class="wxapp-toast-content">
- <view class="wxapp-toast-content-text">
- {{toastText}}
- </view>
- </view>
- </view>
- <!--wxapp-toast end-->
- </view>
(或者說把這段放到footer.wxml里,每個文件用include引用一下)
四、然后在對應的js文件放一條代碼:(比如對應的index.js)
app.showToast('我是自定義的Toast',that,2000);
五、效果:
新聞熱點
疑難解答