我想在点击时更改文字的颜色。任何人都可以告诉我为什么这段代码不起作用?
<html>
<body>
<center>
<div id="web" style="color:black" onclick="changeformat(this.id)"> Web </div>
<div id="img" style="color:blue" onclick="changeformat(this.id)"> Images </div>
<div id="news" style="color:blue" onclick="changeformat(this.id)"> News </div>
</center>
</body>
</html>
<script>
function changeformat(type)
{
document.getElementById('web').style = "color:blue;";
document.getElementById('img').style = "color:blue";
document.getElementById('news').style = "color:blue";
document.getElementById(type).style = "color:black";
}
</script>
答案 0 :(得分:1)
你几乎拥有它,使用element.style.color
function changeformat(type) {
document.getElementById('web').style.color = "blue;";
document.getElementById('img').style.color = "blue";
document.getElementById('news').style.color = "blue";
document.getElementById(type).style.color = "black";
}
Derek指出你也可以使用element.setAttribute()
,这将覆盖已经在元素上设置的其他内联样式。
function changeformat(type) {
document.getElementById('web').setAttribute("style", "color:blue;");
document.getElementById('img').setAttribute("style", "color:blue");
document.getElementById('news').setAttribute("style", "color:blue");
document.getElementById(type).setAttribute("style", "color:black");
}
答案 1 :(得分:1)
试试这个,它会起作用。更改颜色的正确方法是使用:document.getElementById(id).style.color
<html>
<body>
<center>
<div id="web" style="color:black" onclick="changeformat(this.id)"> Web </div>
<div id="img" style="color:blue" onclick="changeformat(this.id)"> Images </div>
<div id="news" style="color:blue" onclick="changeformat(this.id)"> News </div>
</center>
</body>
</html>
<script>
function changeformat(type)
{
document.getElementById('web').style.color = "blue";
document.getElementById('img').style.color = "blue";
document.getElementById('news').style.color = "blue";
document.getElementById(type).style.color = "black";
}
</script>
答案 2 :(得分:0)
<div id="web" style="color:black" onclick="changeformat(this)"> Web </div>
<div id="img" style="color:blue" onclick="changeformat(this)"> Images </div>
<div id="news" style="color:blue" onclick="changeformat(this)"> News </div>
function changeformat(element) {
var elements = ['web', 'img', 'news'];
for( var i = 0, length = elements.length; i < length; i++ ) {
document.getElementById( elements[i] ).style.color = 'blue';
}
element.style.color = "black";
}
答案 3 :(得分:0)
您必须以这种方式设置颜色:
//element.style.CSSProperty = Value;
ele.style.color = "blue";
优化版本:
<div id="web" style="color:black" onclick="changeformat(event)"> Web </div>
function changeformat(e){
var eles = document.querySelectorAll("div");
for(var i = 0 ; i < eles.length; i++){
eles[i].style.color = "blue";
}
e.target.style.color = "black";
}
答案 4 :(得分:0)
试试这段代码
function changeformat(type)
{
document.getElementById('web').style.color = 'green';
document.getElementById('img').style.color = 'pink';
document.getElementById('news').style.color = 'red';
document.getElementById(type).style.color = "black";
}