原文在这里: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;
}