function changeColor(){
var box = document.getElementById("size");
box.style.background-color ="yellow";
}
#size{
width: 100px;
height:100px;
transition: all 1s;
cursor: pointer;
}
<div style="background-color: pink;" id="size" onclick="changeColor()">
</div>
我正在学习javascript,我处于非常基本的水平。我正在制作一个javascipt函数,当用户单击div时,它会改变颜色。但即使是这段简单的代码也不起作用。请在我提交问题的地方提供帮助。谢谢
你应该使用:
box.style.backgroundColor ="yellow";
您需要
更改box.style.background-color ="yellow";
到box.style.backgroundColor ="yellow";
有关完整的属性列表,请参见此处
function changeColor(){
var box = document.getElementById("size");
box.style.backgroundColor ="yellow";
}
#size{
width: 100px;
height:100px;
transition: all 1s;
cursor: pointer;
}
<div style="background-color: pink;" id="size" onclick="changeColor()">
</div>
您也可以将该属性用作[]
中的字符串:
function changeColor(){
var box = document.getElementById("size");
box.style["background-color"] ="yellow";
}
#size{
width: 100px;
height:100px;
transition: all 1s;
cursor: pointer;
}
<div style="background-color: pink;" id="size" onclick="changeColor()">
</div>