微信小程序button的可用不可用动态实现

2018-04-25  本文已影响0人  jackli007

微信小程序button的可用不可用动态实现

需求】:在做微信小程序开发时,要求用户登录需要输入账号和密码,且账号和密码的input有内容时,登录按钮才可点击。即需要动态地实现button的disable属性为truefalse。需求如下:

image

实现思路】:
(1)在app.js中定义两个全局的Boolean型变量:

(2)在登录页面的page的login.js中两个input的绑定函数中,对其对应的上述的全局变量进行赋值。然后将该两个全局编辑进行逻辑与或者逻辑或的操作,并将该结果赋给button的disable。

代码实现】直接上代码

// app.js
App({
  globalData: {
    useridLength: false,
    passwdLength: false,
  },
});
<!-- login.wxml -->
<view class="bd" style="flex:2;">
  <form class="login-form">
    <view class="input-group {{userid_focus ? 'active' : ''}}">
      <text class="input-label">帐号</text>
      <input type="number" cursor-spacing="30" id="userid" maxlength="20" placeholder="请输入手机号/邮箱/用户名" bindinput="useridInput" bindfocus="inputFocus" bindblur="inputBlur" />
    </view>
    <view class="input-group {{passwd_focus ? 'active' : ''}}">
      <text class="input-label">密码</text>
      <input password="true" cursor-spacing="30" id="passwd" placeholder="请输入密码" bindinput="passwdInput" bindfocus="inputFocus" bindblur="inputBlur" />
    </view>
  </form>
  <button class="confirm-btn" style="opacity :{{opacity}};  background: #ED6D2C; color: #fff;" bindtap="bind" disabled="{{disable}}">
      登录
  </button>
</view>
//login.js
//获取应用实例
var app = getApp();
Page({
  data: {
    userid_focus: false,
    passwd_focus: false,
    userid: '',
    passwd: '',
    disable:true,
    opacity: .4,
  },
  useridInput: function (e) {
    if (e.detail.value.length > 0) {
      app.globalData.useridLength = true
    } else {
      app.globalData.useridLength = false
    } 
    this.setData({
      userid: e.detail.value,
      disable: !(app.globalData.useridLength & app.globalData.passwdLength),
      opacity: !(app.globalData.useridLength & app.globalData.passwdLength) == true ? 0.4 : 0.9
    });
  },
  passwdInput: function (e) {
    if (e.detail.value.length > 0) {
      app.globalData.passwdLength = true
    } else {
      app.globalData.passwdLength = false
    }
    this.setData({
      passwd: e.detail.value,
      disable: !(app.globalData.useridLength & app.globalData.passwdLength),
      opacity: !(app.globalData.useridLength & app.globalData.passwdLength) == true ? 0.4 : 0.9
    });
  },
  inputFocus: function (e) {
    if (e.target.id == 'userid') {
      this.setData({
        'userid_focus': true
      });
    } else if (e.target.id == 'passwd') {
      this.setData({
        'passwd_focus': true
      });
    }
  },
  inputBlur: function (e) {
    if (e.target.id == 'userid') {
      this.setData({
        'userid_focus': false
      });
    } else if (e.target.id == 'passwd') {
      this.setData({
        'passwd_focus': false
      });
    }
  }
});
上一篇下一篇

猜你喜欢

热点阅读