正如標題所示,我試圖使用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所示),然後我想在打印之前將其更改爲綠色。但是代碼不起作用。我不知道錯誤在哪裏。
一個良好的開端是審查你的JS教程,和骨上來就變量'green'和字符串''green''之間的區別。 – 2014-10-08 05:08:17