如标题所示,我正在尝试使用 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 所建议的),然后我想在打印之前将其更改为绿色。但是代码不起作用。我不知道错误在哪里。
最佳答案
需要先制作第一个item
:
<div id="item">I am a potato</div>
<script>
//...stuff....
</script>
然后我们需要使用字符串:
changeBG("item","green")
最后在 JavaScript 中我们说 backgroundColor
而不是 background-color
。
关于javascript - 使用 Javascript 更改 CSS 背景色,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26249488/