首页 > 课堂 > 小程序 > 正文

微信小程序自定义toast代码开发实用组件/插件

2020-03-21 16:20:29
字体:大 中 小
来源:转载
供稿:网友

微信小程序自定义toast代码开发实用组件/插件。

小程序交互仅提供这些API

微信小程序,小程序开发,toast,组件

wx.showToast的效果是这样的,太难看了

微信小程序,小程序开发,toast,组件

现在我们来自己写个toast

一、我们把样式写在app.wxss里,这样每个地方都可以调用到

  1. /*toast start*/ 
  2.  
  3. .wxapp-toast-mask{ 
  4.  
  5. opacity: 0; 
  6.  
  7. width: 100%; 
  8.  
  9. height: 100%; 
  10.  
  11. overflow: hidden; 
  12.  
  13. position: fixed; 
  14.  
  15. top: 0; 
  16.  
  17. left: 0; 
  18.  
  19. z-index: 888; 
  20.  
  21. } 
  22.  
  23. .wxapp-toast-content-box { 
  24.  
  25. display: flex; 
  26.  
  27. width: 100%; 
  28.  
  29. height: 100%; 
  30.  
  31. justify-content: center; 
  32.  
  33. align-items: center; 
  34.  
  35. position: fixed; 
  36.  
  37. z-index: 999; 
  38.  
  39. } 
  40.  
  41. .wxapp-toast-content { 
  42.  
  43. width: 50%; 
  44.  
  45. padding: 20rpx; 
  46.  
  47. background: rgba(0, 0, 0, 0.7); 
  48.  
  49. border-radius: 20rpx; 
  50.  
  51. } 
  52.  
  53. .wxapp-toast-content-text { 
  54.  
  55. height: 100%; 
  56.  
  57. width: 100%; 
  58.  
  59. color: #fff; 
  60.  
  61. font-size: 28rpx; 
  62.  
  63. text-align: center; 
  64.  
  65. } 
  66.  
  67. /*toast end*/ 

二、JS也是写在在app.js里:

  1. //自定义Toast 
  2.  
  3. showToast: function(text,o,count){ 
  4.  
  5. var _this = o; 
  6.  
  7. count = parseInt(count) ? parseInt(count) : 3000; 
  8.  
  9. _this.setData({ 
  10.  
  11. toastText:text, 
  12.  
  13. isShowToast: true, 
  14.  
  15. }); 
  16.  
  17. setTimeout(function () { 
  18.  
  19. _this.setData({ 
  20.  
  21. isShowToast: false 
  22.  
  23. }); 
  24.  
  25. },count); 
  26.  
  27. }, 

三、在需要调用的wxml文件中合适的地方加上下面代码:(比如index.wxml,注意:有container要放在里面)
 

  1. <view class="container"> 
  2.     <!--wxapp-toast start--> 
  3.     <view class="wxapp-toast-content-box" wx:if="{{isShowToast}}"> 
  4.     <view class="wxapp-toast-content"> 
  5.         <view class="wxapp-toast-content-text"> 
  6.         {{toastText}} 
  7.         </view> 
  8.     </view> 
  9.     </view> 
  10.     <!--wxapp-toast end--> 
  11. </view> 

(或者说把这段放到footer.wxml里,每个文件用include引用一下)

微信小程序,小程序开发,toast,组件

四、然后在对应的js文件放一条代码:(比如对应的index.js)

app.showToast('我是自定义的Toast',that,2000);

五、效果:

微信小程序,小程序开发,toast,组件


发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表