[英]Change CSS background-color using Javascript
如标题所示,我正在尝试使用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
。
@media print {
#item {
background-color:green;
}
}
将此包含在您的CSS中。 这将解决打印时的问题。
javascript中的所有css属性都是驼峰式的,而不是脊柱式的
document.getElementById('youElement').style.backgroundColor = 'color';
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.