小程序學習:點擊文本,切換顏色

原文在這裏:https://blog.csdn.net/Duan_Super/article/details/79390683

 

實現點擊 hello 文本,文本顏色在紅色和綠色間切換。

對自動生成的模板,修改三個文件內容即可。

index.js  內容:

//index.js
//獲取應用實例
const app = getApp()
var flag = true;
var color;

Page({
  data: {
    motto: 'Hello World',
    userInfo: {},
    hasUserInfo: false,
    canIUse: wx.canIUse('button.open-type.getUserInfo'),
    color: "window"
  },
  //事件處理函數
  click: function () {
    console.log("點擊了文字");
    if(flag){
      color = "window-red";
      flag = false;
    }else{
      color = "window-green";
      flag = true;
    }
    this.setData({
      color
    })
  },
  bindViewTap: function() {
    wx.navigateTo({
      url: '../logs/logs'
    })
  },
  onLoad: function () {
    if (app.globalData.userInfo) {
      this.setData({
        userInfo: app.globalData.userInfo,
        hasUserInfo: true
      })
    } else if (this.data.canIUse){
      // 由於 getUserInfo 是網絡請求,可能會在 Page.onLoad 之後才返回
      // 所以此處加入 callback 以防止這種情況
      app.userInfoReadyCallback = res => {
        this.setData({
          userInfo: res.userInfo,
          hasUserInfo: true
        })
      }
    } else {
      // 在沒有 open-type=getUserInfo 版本的兼容處理
      wx.getUserInfo({
        success: res => {
          app.globalData.userInfo = res.userInfo
          this.setData({
            userInfo: res.userInfo,
            hasUserInfo: true
          })
        }
      })
    }
  },
  getUserInfo: function(e) {
    console.log(e)
    app.globalData.userInfo = e.detail.userInfo
    this.setData({
      userInfo: e.detail.userInfo,
      hasUserInfo: true
    })
  }
})

上面內容中增加的部分:

...
var flag = true;
var color;
...
    color: "window"
...
  click: function () {
    console.log("點擊了文字");
    if(flag){
      color = "window-red";
      flag = false;
    }else{
      color = "window-green";
      flag = true;
    }
    this.setData({
      color
    })
  },
...

index.wxml  文件增加以下內容(包含在 container 部分,位於最下方),:

  <view  class="usermotto">
    <text catchtap="click" class="{{color}}">Hello</text>
  </view>

index.wxss 文件增加以下內容:


.window-green{
    color:rgb(26, 219, 90);
}

.window-red{
    color:#D23933;
}

 

 

 

 

 

 

 

 

 

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