Javascript 为什么不是';这不是在改变背景吗?
具体来说,我想做的是使用calcR()函数生成的随机值更改背景。 下面是我为此编写的代码Javascript 为什么不是';这不是在改变背景吗?,javascript,css,Javascript,Css,具体来说,我想做的是使用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);
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})`;
}
}
要向您展示一个端到端的示例,应该这样做:
CB类{
构造函数(){
this.backround=“绿色”;
}
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();
函数changeBG(){
cbInstance.calcR();
cbInstance.cbg();
}
更改bg
您可以这样做以实现您的结果:
CB类{
构造函数(){
this.backround=“绿色”;
}
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=新的cb();
cb.calcR().cbg()代码>嗯。。。您已经定义了一个类。。。您在哪里实例化了它?然后运行calcR
,然后再运行cbg
?您需要导入该类,创建一个实例,调用calcR
并调用cbg
,然后再做任何事情。请说明您是如何使用该类的-因为类定义也不会“运行”,请检查browser developer tools控制台中的错误单击此链接查看我在做什么,将相关代码放入问题中