2014-10-08 172 views
-1

正如標題所示,我試圖使用JavaScript函數更改我的CSS背景顏色。爲了簡化這個問題,我在這裏寫了一個新的代碼。使用Javascript更改CSS背景顏色

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> 
<html xmlns="http://www.w3.org/1999/xhtml"> 
<head> 
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" /> 
<title>Potato</title> 

<style> 
#item { 
    background-color:blue; 
    color:red; 
} 
</style> 

<script type="text/javascript"> 
    function changeBG(id,color) { 
     var id = id; 
     var color = color; 

     document.getElementById(id).style.background-color = color; 
    } 
</script> 
</head> 

<body> 
<script type="text/javascript">changeBG(item,green)</script> 
<div id="item">I am a potato</div> 
</body> 
</html> 

默認的背景顏色是紅色的(如CSS所示),然後我想在打印之前將其更改爲綠色。但是代碼不起作用。我不知道錯誤在哪裏。

+0

一個良好的開端是審查你的JS教程,和骨上來就變量'green'和字符串''green''之間的區別。 – 2014-10-08 05:08:17

回答

1

首先item首先需要做:

<div id="item">I am a potato</div> 
<script> 
    //...stuff.... 
</script> 

這時我們就需要使用字符串:

changeBG("item","green") 

最後在JavaScript中,我們說backgroundColor以外background-color

+0

謝謝老兄,它的工作原理! – 2014-10-08 05:11:54

0

在JavaScript中所有的CSS屬性駝峯格式,而不是脊柱外裝

document.getElementById('youElement').style.backgroundColor = 'color'; 
1
@media print { 
    #item { 
    background-color:green; 
    } 
} 

在你的CSS包含此。這將在打印時解決您的問題。

0

使用jQuery

$("#item").css("background-color", "green"); 

Documentation

或者純JavaScript

document.getElementById("item").style.backgroundColor = "green"; 

Documentation