使用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>

最佳答案

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



function foo(){
  document.getElementById("head1").className = "newclass";
  }

h1{background:gold;}
h1.newclass{background:green;}

<h1 id="head1">This is a heading</h1>
<button onclick="foo()">Click!</button>

10-05 19:46