微信小程序(二)

 **********************************************

一、遮罩層穿透滾動

描述:當彈出彈窗類似的東西時,滑動的時候,被遮罩遮住的底層不讓其滾動。

穿透分爲兩種

a.彈窗中沒有scroll-view標籤

在遮罩層加屬性catchtouchmove

<view catchtouchmove="myCatchTouch">
    <template is="alert" />
</view>

myCatchTouch: function () {
  console.log('stop user scroll it!');
  return;
},

b.彈窗中有scroll-view標籤(上述)

通過參數判斷一下,遮罩彈出的時候加一個樣式

<view class='{{clickHide? "" : "bodyLock"}} myContainer heightTop' wx:if="{{changeRecordList.length!=0}}">

/* 背景固定 */
.bodyLock{
  top:0px;
  left: 0px;
  width: 100%;
  height: 100%;
  overflow: hidden;
  position: fixed;
  z-index: 0;
}

二、echarts圖自適應居中

在小程序中讓雷達圖居中,不同手機都居中

//獲取設備信息
var sys = wx.getSystemInfoSync();
var mW = sys.windowWidth;
var mH = sys.windowHeight;

//在需要的位置,適當調整
radius: mW*0.25,
center: ['47%', '47%'], // 圖的位置

三、循環數組操作當前

思路:
1.給數組每一項加一個變量
2.單獨操作當前的變量

//給當前數組加變量
var list = res.data;
for (var i = 0; i < list.length; i++) {
   list[i].isOpen = false;
   list[i].isClose = true;
}

四、調用接口

每次請求的參數大多相同,可以寫成公用方法使用。

請求分爲:post get

post:數據量大 安全 (登錄一般使用)
get:地址訪問 

post請求 

//post請求
function postReq(url, data, cb) {

  var token = app.globalData.token;
  var username = app.globalData.username;
  if (token == undefined) {
    token = '';
  }
  data.username = username;
  data.token = token;
  data.loginType = 1
  wx.request({
    url: rootDocment + url,
    data: data,
    method: 'post',
    header: {
      'Content-Type': 'application/x-www-form-urlencoded'
    },
    success: function(res) {
      if (res.data.code == '207') {
        app.globalData.token = '1c14f665aa8643c28f899aa9b0efee56';
        app.globalData.username = '';
        wx.showModal({
          content: res.data.desc,
          confirmColor: '#007aff',
          cancelColor: '#007aff',
          confirmText: '去登錄',
          cancelText: '取消',
          success: function(res) {
            if (res.confirm) {
              setTimeout(function() {
                wx.navigateTo({
                  url: '/pages/comment/pages/login/login',
                })
              }, 1000);
            } else if (res.cancel) {
              wx.switchTab({
                url: '/pages/tabBar/homePage/homePage',
              })
            }
          }
        })
      } else {
        return typeof cb == "function" && cb(res.data)
      }
    },
    fail: function(e) {
      wx.showToast({
        title: '系統維護中!',
        duration: 2000
      });
      return typeof cb == "function" && cb(false)
    },
  })
}

 get請求

//get請求
function getReq(url, data, cb) {
  var token = app.globalData.token;
  var username = app.globalData.username;
  if (token == undefined) {
    token = '';
  }
  data.username = username;
  data.token = token;
  data.loginType = 1
  wx.request({
    url: rootDocment + url,
    data: data,
    method: 'get',
    header: {
      'Content-Type': 'application/x-www-form-urlencoded'
    },
    success: function(res) {
      if (res.data.code == '207') {
        app.globalData.token = '1c14f665aa8643c28f899aa9b0efee56';
        app.globalData.username = '';
        wx.showModal({
          content: res.data.desc,
          confirmColor: '#007aff',
          cancelColor: '#007aff',
          confirmText: '去登錄',
          cancelText: '取消',
          success: function(res) {
            if (res.confirm) {
              setTimeout(function() {
                wx.navigateTo({
                  url: '/pages/comment/pages/login/login',
                })
              }, 1000);
            } else if (res.cancel) {
              wx.switchTab({
                url: '/pages/tabBar/homePage/homePage',
              })
            }
          }
        })
      } else {
        return typeof cb == "function" && cb(res.data)
      }

    },
    fail: function(e) {
      wx.showToast({
        title: '系統維護中!',
        duration: 2000
      });
      return typeof cb == "function" && cb(false)
    },
  })
}

五、導航欄切換

  <!--導航欄-->
  <view class="riskTab">
    <view wx:for="{{navBar}}" wx:for-item='item' data-idx="{{index}}" class="riskTabList" wx:key="unique" bindtap="navbarTap">{{item}}</view>
  </view>

/**切換欄**/
.riskTab{display: flex; height: 98rpx; line-height: 98rpx; border-bottom: 1px solid #a6a6a6; background: #fff; box-shadow:0rpx 3rpx 3rpx 3rpx #e7e7e7; position:fixed; background-color:#ffffff; z-index:99; width:100%; } 
.riskTab .riskTabList{flex: 1; height: 98rpx; line-height: 98rpx; text-align: center; position: relative; box-sizing: border-box; } 
.riskTab .riskTabList.on{color: #085ea9; border-bottom: 3rpx solid #085ea9; }

/*切換*/
Page({
  data: {
    navBar: ['行業', '產品', '地區'],
  },
  //導航欄切換
  navbarTap: function(e) {
    var _id = e.currentTarget.dataset.idx;
    this.setData({
      currentTab: _id,
      toView: 'toView' + _id
    })
  },
})

六、樣式切換

<view class="{{xxx?"":""}}"></view>

七、彈窗

小程序中有自帶的彈窗

有4種類型的彈窗供我們使用

頁面

<span style="font-family:Comic Sans MS;font-size:18px;color:#333333;"><view class="container" class="zn-uploadimg">  
    <button type="primary"bindtap="showok">消息提示框</button>   
    <button type="primary"bindtap="modalcnt">模態彈窗</button>   
    <button type="primary"bindtap="actioncnt">操作菜單</button>   
</view></span>

 

1.wx.showModal(OBJECT)---消息提示框

 

//提示窗
showok:function() {  
   wx.showToast({  
        title: '成功',  
        icon: 'success',  
        duration: 2000  
   })  
} 

 

 

2.wx.showModal(OBJECT)---模態彈窗

  // 模態彈窗
  modalcnt: function () {
    wx.showModal({
      title: '提示',
      content: '這是一個模態彈窗',
      success: function (res) {
        if (res.confirm) {
          console.log('用戶點擊確定')
        } else if (res.cancel) {
          console.log('用戶點擊取消')
        }
      }
    })
  } 

 

 

3.wx.showActionSheet(OBJECT)---操作菜單

//操作菜單
actioncnt:function(){  
    wx.showActionSheet({  
       itemList: ['A', 'B', 'C'],  
       success: function(res) {  
           console.log(res.tapIndex)  
       },  
       fail: function(res) {  
           console.log(res.errMsg)  
       }  
    })  
} 

 

4.modal---交互彈窗

<view class="container" class="zn-uploadimg">  
    <button type="primary"bindtap="modalinput">modal有輸入框</button>   
</view>  
<modal hidden="{{hiddenmodalput}}" title="請輸入驗證碼" confirm-text="提交" cancel-text="重置" bindcancel="cancel" bindconfirm="confirm">  
    <input type='text'placeholder="請輸入內容" auto-focus/>  
</modal> 


var app = getApp()
Page({
  data: {
    hiddenmodalput: true,
    //可以通過hidden是否掩藏彈出框的屬性,來指定那個彈出框  
  },
  //點擊按鈕痰喘指定的hiddenmodalput彈出框  
  modalinput: function () {
    this.setData({
      hiddenmodalput: !this.data.hiddenmodalput
    })
  },
  //取消按鈕  
  cancel: function () {
    this.setData({
      hiddenmodalput: true
    });
  },
  //確認  
  confirm: function () {
    this.setData({
      hiddenmodalput: true
    })
  }

})  

 

參考文章

八、橫向切換

原文鏈接   我在此基礎上進行修改簡化

<view>
  <view class="tab-h">
    <view class="tab-item {{currentTab==0?'active':''}}"data-current="0" bindtap="swichNav">健康</view>
    <view class="tab-item {{currentTab==1?'active':''}}"data-current="1" bindtap="swichNav">情感</view>
    <view class="tab-item {{currentTab==2?'active':''}}"data-current="2" bindtap="swichNav">職場</view>
  </view>
  <swiper class="tab-content" current="{{currentTab}}" duration="300" bindchange="switchTab">
    <swiper-item wx:for="{{[0,1,2]}}">
      <view class="item-ans">
          <view class="avatar">
              <image class="img" src="http://ookzqad11.bkt.clouddn.com/avatar.png"></image>
          </view>
      </view>
    </swiper-item>
  </swiper>
</view>
var app = getApp();
Page({
  data: {
    currentTab: 0, //預設當前項的值
    expertList: [{ //假數據
      img: "avatar.png",
    }]
  },
  // 滾動切換標籤樣式
  switchTab: function (e) {
    this.setData({
      currentTab: e.detail.current
    });
  },
  // 點擊標題切換當前頁時改變樣式
  swichNav: function (e) {
    var cur = e.target.dataset.current;
    if (this.data.currentTab == cur) { 
      return false;
    }else {
      this.setData({
        currentTab: cur
      })
    }
  }
})
.tab-h{
    height: 80rpx;width: 100%; box-sizing: border-box;overflow: hidden;line-height: 80rpx;background: #F7F7F7; font-size: 16px; white-space: nowrap;position: fixed;top: 0; left: 0; z-index: 99;}
.tab-item{margin:0 36rpx;display: inline-block;}
.tab-item.active{color: #4675F9;position: relative;}
.tab-item.active:after{ content: "";display: block;height: 8rpx;width: 52rpx;background: #4675F9;position: absolute; bottom: 0;left: 5rpx;border-radius: 16rpx;}
.item-ans{ width: 100%;display: flex; flex-grow: row no-wrap;justify-content: space-between; padding: 30rpx;box-sizing: border-box; height: 180rpx;align-items: center;border-bottom: 1px solid #F2F2F2;}
.avatar{width: 100rpx;height: 100rpx;position: relative;padding-right: 30rpx;}
.avatar .img{width: 100%;height: 100%;}
.tab-content{margin-top: 80rpx;}

 

( 我不會錄動態圖 可以試一下)

九、數字轉字符串

1.value.toString()
    不能把null和undefined轉換爲字符串
    string_value = number.toString();

2."" + value
    可讀性較差
    var n = 100;
    var n_as_string = n + "";

3.String(value)
    可讀性更好
    var string_value = String(number);

十、左滑刪除

 

<view class="container">
  <view class="touch-item {{item.isTouchMove ? 'touch-move-active' : ''}}" data-index="{{index}}" bindtouchstart="touchstart" bindtouchmove="touchmove" wx:for="{{items}}" wx:key="">
  <view class="content">{{item.content}}</view>
  <view class="del" catchtap="del" data-index="{{index}}">刪除</view>
  </view>
</view>
page {
  background-color: white;  
}
.container {
  min-height: 100%;
  padding: 20rpx 0rpx;
}
.touch-item {
  font-size: 14px;
  display: flex;
  justify-content: space-between;
  border-bottom:1px solid #ccc;
  width: 100%;
  overflow: hidden;
}

.content {
  width: 100%;
  padding: 10px;
  line-height: 22px;
  margin-right:0;
  -webkit-transition: all 0.4s;
  transition: all 0.4s;
  -webkit-transform: translateX(90px);
  transform: translateX(90px);
  margin-left: -90px;
}

.del {
  background-color: orangered;
  width: 90px;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  color: #fff;
  -webkit-transform: translateX(90px);
  transform: translateX(90px);
  -webkit-transition: all 0.4s;
  transition: all 0.4s;
}
.touch-move-active .content,
.touch-move-active .del {
  -webkit-transform: translateX(0);
  transform: translateX(0);
}

主要方法:touchmove、touchstart、angle 

Page({
  data: {
    items: [],
    startX: 0, //開始座標
    startY: 0
  },
  onLoad: function (e) {
    var that = this;
    for (var i = 0; i < 10; i++) {
      this.data.items.push({
        content: i + " 向左滑動刪除哦,向左滑動刪除哦,向左滑動刪除哦,向左滑動刪除哦,向左滑動刪除哦",
        isTouchMove: false //默認隱藏刪除
      })
    }
    this.setData({
      items: this.data.items
    });
  },
  //手指觸摸動作開始 記錄起點X座標
  touchstart: function (e) {
    //開始觸摸時 重置所有刪除
    this.data.items.forEach(function (v, i) {
      if (v.isTouchMove)//只操作爲true的
        v.isTouchMove = false;
    })
    this.setData({
      startX: e.changedTouches[0].clientX,
      startY: e.changedTouches[0].clientY,
      items: this.data.items
    })
  },
  //滑動事件處理
  touchmove: function (e) {
    var that = this,
      index = e.currentTarget.dataset.index,//當前索引
      startX = that.data.startX,//開始X座標
      startY = that.data.startY,//開始Y座標
      touchMoveX = e.changedTouches[0].clientX,//滑動變化座標
      touchMoveY = e.changedTouches[0].clientY,//滑動變化座標
      //獲取滑動角度
      angle = that.angle({ X: startX, Y: startY }, { X: touchMoveX, Y: touchMoveY });
      that.data.items.forEach(function (v, i) {
        v.isTouchMove = false
        //滑動超過30度角 return
        if (Math.abs(angle) > 30) return;
          if (i == index) {
            if (touchMoveX > startX) //右滑
              v.isTouchMove = false
        else //左滑
          v.isTouchMove = true
      }
    })
    //更新數據
    that.setData({
      items: that.data.items
    })
  },
  /**
  * 計算滑動角度
  */
  angle: function (start, end) {
    var _X = end.X - start.X,
      _Y = end.Y - start.Y
    //返回角度 /Math.atan()返回數字的反正切值
    return 360 * Math.atan(_Y / _X) / (2 * Math.PI);
  },
  //刪除事件
  del: function (e) {
    this.data.items.splice(e.currentTarget.dataset.index, 1)
    this.setData({
      items: this.data.items
    })
  }

})

十一、表單

十二、媒體組件

十三、全屏

需求:在裏面的內容不是全屏的情況下,外部的height設爲全屏

Page{
    height:100%;
}

.xxx{
    height:100%;
}


<view class='xxx'></view>

注:不能設成min-height,否則不起作用

十四、方法中傳e

需求:一個方法調用另一個方法,往中傳遞e。


a:function(e){
    var that=this;
    that.b(e);
}

b:function(e){
    var e=e.currentTarget.dataset.xxx;
}

十五、返回上一頁面數據刷新

數據有更新變化的,放到onShow:function(){}中顯示

或者

onShow:function(){
    this.onLoad();
}

 十六、手機禁止滑動

在ios系統中,手機有滑動效果,但這樣有時會影響整體樣式,就需要禁止其滑動

在所屬json中加

    "disableScroll": true

十七、點擊小程序左上角觸發事件

在小程序中,其實沒有對點擊左上角觸發的專門事件,但是可以通過標識、onShow、onHide來模擬點擊左上角觸發事件

 

a頁面進入b頁面,從b頁面退出到a頁面。

思路:
    1.在app.js中給一個標識--false
    2.進入b頁面 onShow--true onHide--false
    3.退出b頁面 進入a頁面 進行相應的操作 並在onShow--false

----------------------------------------------------------

app.js
App({
    aData:{
      show:false
    },
})

b頁面
onShow() {
  app.aData.show = true;
},
onHide() {
  app.aData.show = false;
},


a頁面
onShow(options) {  
    let self = this;
    let aShow = app.aData.show;
    if (aShow){
         app.aData.show = false;
         
         //進行操作
    }
  }

十八、小程序的生命週期

官方文檔

生命週期回調函數
onLoad()   頁面加載,接收傳遞到頁面的參數。一個頁面只會調用一次。
onShow()   頁面數據顯示的時候加載。
onReady()  頁面初次渲染加載完畢,可以與視圖層進行交互。一個頁面只會調用一次。
onHide()   頁面隱藏或切入後臺的時候。比如進入其他頁面。
onUnload() 頁面卸載的時觸發。如redirectTo 或navigateBack到其他頁面。

----------------------------------------------------------------

頁面事件處理函數
onPullDownRefresh()  用戶下拉事件
onReachBottom()      用戶上拉事件
onPageScroll()       用戶滑動頁面事件
onShareAppMessage()  用戶點擊分享事件
onTabItemTap()       用戶點擊tab事件

----------------------------------------------------------------

組件事件處理函數
用戶自己定義的一些函數

注:在小程序中app.js的生命週期是隻執行一次的。

十九、設置tabbar的紅點(數量提示)

設置是系統自帶的 都是一對一對的 有設置就有移除 


文本設置 

  wx.setTabBarBadge(OBJECT)

解釋:爲 tabBar 某一項的右上角添加文本

OBJECT 參數說明:

參數	    類型		說明
index	    Number		tabBar的哪一項,從左邊算起
text	    String		顯示的文本,超過 3 個字符則顯示成“…”
success	    Function	接口調用成功的回調函數
fail	    Function	調用失敗的回調函數
complete	Function	接口調用結束的回調函數(調用成功、失敗都會執行)

wx.removeTabBarBadge(OBJECT)

解釋:移除 tabBar 某一項右上角的文本

OBJECT 參數說明:

參數	    類型		說明
index	    Number		tabBar的哪一項,從左邊算起
success	    Function	接口調用成功的回調函數
fail	    Function	接口調用失敗的回調函數
complete	Function	接口調用結束的回調函數(調用成功、失敗都會執行)

 


紅點設置 

  wx.showTabBarRedDot(OBJECT) 

解釋:顯示 tabBar 某一項的右上角的紅點

OBJECT 參數說明:

參數	    類型		說明
index	    Number		tabBar的哪一項,從左邊算起
success	    Function	接口調用成功的回調函數
fail	    Function	接口調用失敗的回調函數
complete	Function	接口調用結束的回調函數(調用成功、失敗都會執行)

wx.hideTabBarRedDot(OBJECT) 

解釋:隱藏 tabBar 某一項的右上角的紅點

OBJECT 參數說明:

參數	    類型		    說明
index	    Number		    tabBar的哪一項,從左邊算起
success	    Function		接口調用成功的回調函數
fail	    Function		接口調用失敗的回調函數
complete	Function		接口調用結束的回調函數(調用成功、失敗都會執行)

設置tabbar顯示隱藏

wx.showTabBar(OBJECT)

解釋:顯示 tabBar

OBJECT 參數說明:

參數	    類型		    說明
animation	Boolean		    是否需要動畫效果,默認無
success	    Function		接口調用成功的回調函數
fail	    Function		接口調用失敗的回調函數
complete	Function		接口調用結束的回調函數(調用成功、失敗都會執行)

wx.hideTabBar(OBJECT)

解釋:隱藏 tabBar

OBJECT 參數說明:

參數	    類型		    說明
animation	Boolean		    是否需要動畫效果,默認無
success	    Function		接口調用成功的回調函數
fail	    Function		接口調用失敗的回調函數
complete	Function		接口調用結束的回調函數(調用成功、失敗都會執行)

設置樣式

wx.setTabBarStyle(OBJECT)

解釋:動態設置 tabBar 的整體樣式

OBJECT 參數說明:

參數	        類型	    說明
color	        HexColor	tab 上的文字默認顏色
selectedColor	HexColor	tab 上的文字選中時的顏色
backgroundColor	HexColor	tab 的背景色
borderStyle	    String	    tabbar上邊框的顏色, 僅支持 black/white
success	        Function	接口調用成功的回調函數
fail	        Function	接口調用失敗的回調函數
complete	    Function	接口調用結束的回調函數(調用成功、失敗都會執行)

wx.setTabBarItem(OBJECT)

解釋:動態設置 tabBar 某一項的內容

OBJECT 參數說明:

參數	            類型		說明
index	            Number		tabBar 的哪一項,從左邊算起
text	            String		tab 上按鈕文字
iconPath	        String		圖片路徑,icon 大小限制爲40kb,建議尺寸爲 81px * 81px
selectedIconPath	String		選中時的圖片路徑,icon 大小限制爲40kb,建議尺寸爲 81px * 81px 
success	            Function	接口調用成功的回調函數
fail	            Function	接口調用失敗的回調函數
complete	        Function	接口調用結束的回調函數(調用成功、失敗都會執行)

onTabItemTap

解釋:點擊 tab 時觸發

 

**********************更新中************************

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章