2015-05-08 64 views
1

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

<!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> 
+0

研究:http://stackoverflow.com/questions/19943118/difference-between-body-style-backgroundcolor-and-window-getcomputedstylebody – developerCK

+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 第二选项是正确的。

+0

谢谢你的回答。 –

1

如果您使用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>

+0

谢谢你的回答。 –

+0

如果我的回答适合您的要求,那么您可能会接受此答案。这更好,因为我们在这里使用类而不是内联元素。 –

相关问题