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

使用JavaScript HTML DOM更改背景颜色的最佳方法,javascript,css,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> //

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

演示页
这是一个标题
//这个?
document.getElementById(“head1”).style[“背景色”]=“黄色”;
//这个?
document.getElementById(“head1”).style.backgroundColor=“黄色”;
//还是这个?
document.getElementById(“head1”).style.background=“黄色”;

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

函数foo(){
document.getElementById(“head1”).style.backgroundColor=“黄色”;
}

演示页
这是一个标题
点击

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

函数foo(){
document.getElementById(“head1”).style.backgroundColor=“黄色”;
}

演示页
这是一个标题
点击

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

函数foo(){
document.getElementById(“head1”).className=“newclass”;
}
h1{背景:金色;}
h1.newclass{背景:绿色;}
这是一个标题

点击
如果您使用CSS
class
而不是
style
,则有一种更好的方法

函数foo(){
document.getElementById(“head1”).className=“newclass”;
}
h1{背景:金色;}
h1.newclass{背景:绿色;}
这是一个标题

点击研究:谢谢你的评论。研究:谢谢你的评论。谢谢你的回答。谢谢你的回答。谢谢你的回答。如果我的回答符合你的要求,你可以接受这个回答。这更好,因为我们这里使用的是类而不是内联元素。感谢您的回答。如果我的答案符合您的要求,您可能会接受这个答案。这更好,因为我们这里使用的是类,而不是内联元素。