使用JavaScript HTML DOM更改背景颜色的最佳方法

时间:2015-05-08 04:30:32

标签: javascript css

使用JavaScript更改元素背景颜色的最合适和跨浏览器兼容的方法是什么?

<!DOCTYPE html>
<html>
<head>
<title>Demo page</title>
</head>
<body>

<h1 id="head1" style="background-color:red">This is a heading</h1>

<script>

// this one?
document.getElementById("head1").style["background-color"] = "yellow"; 

// this one?
document.getElementById("head1").style.backgroundColor = "yellow";

//or this one?
document.getElementById("head1").style.background = "yellow";

</script>

</body>
</html>

2 个答案:

答案 0 :(得分:3)

获取元素,然后使用.style属性和.backgroundColor属性进行更改:

function foo(){
  document.getElementById("head1").style.backgroundColor = "yellow";
  }
<!DOCTYPE html>
<html>
<head>
<title>Demo page</title>
</head>
<body>

<h1 id="head1" style="background-color:red">This is a heading</h1>
<button onclick="foo()">Click!</button>

</body>
</html>

因此,您的2 nd 选项是正确的。

答案 1 :(得分:1)

如果您使用CSS class而不是style,则有更好的方法。

&#13;
&#13;
function foo(){
  document.getElementById("head1").className = "newclass";
  }
&#13;
h1{background:gold;}
h1.newclass{background:green;}
&#13;
<h1 id="head1">This is a heading</h1>
<button onclick="foo()">Click!</button>
&#13;
&#13;
&#13;