[英]Why isn't this changing the background?
详细地说,我想要做的是使用 calcR() 函数生成的随机值更改背景。 这是我为此编写的代码。
export default class CB {
constructor() {
this.backround = "green";
}
calcR() {
this.r1 = Math.floor(Math.random() * 255 + 1);
this.r2 = Math.floor(Math.random() * 255 + 1);
this.r3 = Math.floor(Math.random() * 255 + 1);
console.log(this.r1);
console.log(this.r2);
console.log(this.r3);
}
cbg() {
document.body.style.background = `rgb(${this.r1}, ${this.r2}, ${this.r3})`;
}
}
为了向您展示端到端示例,这应该有效:
class CB { constructor() { this.backround = "green"; } calcR() { this.r1 = Math.floor(Math.random() * 255 + 1); this.r2 = Math.floor(Math.random() * 255 + 1); this.r3 = Math.floor(Math.random() * 255 + 1); console.log(this.r1); console.log(this.r2); console.log(this.r3); } cbg() { document.body.style.background = `rgb(${this.r1}, ${this.r2}, ${this.r3})`; } } const cbInstance = new CB(); function changeBG() { cbInstance.calcR(); cbInstance.cbg(); }
<button type="button" onClick="javascript:changeBG()">Change bg</button>
你可以做这样的事情来达到你的结果:
class CB { constructor() { this.backround = "green"; } calcR() { this.r1 = Math.floor(Math.random() * 255 + 1); this.r2 = Math.floor(Math.random() * 255 + 1); this.r3 = Math.floor(Math.random() * 255 + 1); this.background = `rgb(${this.r1}, ${this.r2}, ${this.r3})`; return this; } cbg() { document.body.style.background = this.background; return this; } } var cb = new CB(); cb.calcR().cbg();
编辑:查看您希望如何使用它,您可以这样重构上面的代码:
你可以做这样的事情来达到你的结果:
class CB { constructor() { this.backround = "green"; } calcR() { this.r1 = Math.floor(Math.random() * 255 + 1); this.r2 = Math.floor(Math.random() * 255 + 1); this.r3 = Math.floor(Math.random() * 255 + 1); this.background = `rgb(${this.r1}, ${this.r2}, ${this.r3})`; } cbg() { document.body.style.background = this.background; } } var cb = new CB(); cb.calcR(); cb.cbg();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.