微信小程序(二)

16 篇文章 0 订阅
2 篇文章 0 订阅

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

一、遮罩层穿透滚动

描述:当弹出弹窗类似的东西时,滑动的时候,被遮罩遮住的底层不让其滚动。

穿透分为两种

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 时触发

 

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

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值