一 组件 .js
Component({
/**
* 组件的初始数据
*/
data: {
_rgb: { // rgb 的颜色值对象
r: 0,
g: 0,
b: 0
},
fullColor: '0, 0, 0' // 根据 rgb 对象的三个属性,动态计算 fullColor 的值
},
/**
* 组件的方法列表
*/
methods: {
changeR() { // 修改 rgb 对象上 r 属性的值
this.setData({
'_rgb.r': this.data._rgb.r + 5 > 255 ? 255 : this.data._rgb.r + 5
})
},
changeG() { // 修改 rgb 对象上 g 属性的值
this.setData({
'_rgb.g': this.data._rgb.g + 5 > 255 ? 255 : this.data._rgb.g + 5
})
},
changeB() { // 修改 rgb 对象上 b 属性的值
this.setData({
'_rgb.b': this.data._rgb.b + 5 > 255 ? 255 : this.data._rgb.b + 5
})
},
_randomColor() {
this.setData({
_rgb: {
r: Math.floor(Math.random() * 256),
g: Math.floor(Math.random() * 256),
b: Math.floor(Math.random() * 256)
}
})
}
},
// 监听对象中指定属性的变化
observers: {
'_rgb.**': function (obj) { // 监听 rgb 对象上 r、g、b 三个子属性的变化 如果某个对象中需要被监听的属性太多,为了方便,可以使用通配符 ** 来监听对象中所有属性的变化
this.setData({ // 为 data 中的 fullColor 重新赋值
fullColor: `${obj.r}, ${obj.g}, ${obj.b}`
})
}
}
})
二 .wxml 结构
<view style="background-color: rgb({{fullColor}});" class="colorBox">颜色值:{{fullColor}}</view>
<button size="mini" type="default" bindtap="changeR">R</button>
<button size="mini" type="primary" bindtap="changeG">G</button>
<button size="mini" type="warn" bindtap="changeB">B</button>
三 .wxss 样式
.colorBox {
line-height: 200rpx;
font-size: 24rpx;
color: white;
text-shadow: 0rpx 0rpx 2rpx black;
text-align: center;
}
四 测试效果