如果我们想实现点击按钮就改变颜色,就可以将颜色变量设置为如下代码,或者声明一个函数。
let colorStr = `rgb(${Math.floor(Math.random() * 256)}, ${Math.floor(Math.random() * 256)}, ${Math.floor(Math.random() * 256)})`
例如在vue中实现点击文字改变背景颜色。
<p @click="changeColor" :style="{backgroundColor:colorStr}">点击我改变背景颜色</p>
<script>
export default {
data() {
return {
colorStr: ''
}
},
methods: {
changeColor() {
this.colorStr = `rgb(${Math.floor(Math.random() * 256)}, ${Math.floor(Math.random() * 256)}, ${Math.floor(Math.random() * 256)})`
}
},
}
</script>