使用 JavaScript (DOM) 更改颜色
change color using JavaScript (DOM)
const box = document.getElementsByClassName('box');
let colorAsString = '#FEC6F0';
let colorAsNumber = #FEC6F0;
Array.from(box).forEach((element) =>{
element.style.backgroundColor = colorAsString;
element.style.backgroundColor = colorAsNumber;
});
我在字符串中存储了一个十六进制颜色值和一个数字,并将该变量作为 css 属性 的值传递。
为什么这段代码不起作用你能解释一下吗...!
当你编辑样式属性时,它最终只是一个CSS字符串。因此,要表示颜色,您可以使用以下格式:'#ffffff' 或 'rgb(255,255,255)'。但是你不能使用数字。
您可以在此处阅读更多相关信息:
https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/style
const box = document.getElementsByClassName('box');
let colorAsString = '#FEC6F0';
Array.from(box).forEach((element) =>{
element.style.backgroundColor = colorAsString;
});
.box {
width:100px;
height:100px;
margin:10px;
background-color:gray;
}
<div class="box"></div>
<div class="box"></div>
<div class="box"></div>
有效
<html>
<body>
<p id="p">
on click change my color
</p>
<script>
onclick = function(){
document.getElementById("p").style.color = "#fff";
document.getElementById("p").style.background = "#000";
}
</script>
</body>
</html>
const box = document.getElementsByClassName('box');
let colorAsString = '#FEC6F0';
let colorAsNumber = #FEC6F0;
Array.from(box).forEach((element) =>{
element.style.backgroundColor = colorAsString;
element.style.backgroundColor = colorAsNumber;
});
我在字符串中存储了一个十六进制颜色值和一个数字,并将该变量作为 css 属性 的值传递。 为什么这段代码不起作用你能解释一下吗...!
当你编辑样式属性时,它最终只是一个CSS字符串。因此,要表示颜色,您可以使用以下格式:'#ffffff' 或 'rgb(255,255,255)'。但是你不能使用数字。
您可以在此处阅读更多相关信息: https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/style
const box = document.getElementsByClassName('box');
let colorAsString = '#FEC6F0';
Array.from(box).forEach((element) =>{
element.style.backgroundColor = colorAsString;
});
.box {
width:100px;
height:100px;
margin:10px;
background-color:gray;
}
<div class="box"></div>
<div class="box"></div>
<div class="box"></div>
有效
<html>
<body>
<p id="p">
on click change my color
</p>
<script>
onclick = function(){
document.getElementById("p").style.color = "#fff";
document.getElementById("p").style.background = "#000";
}
</script>
</body>
</html>