【发布时间】:2017-08-15 14:24:07
【问题描述】:
我想通过使用带有 JavaScript 的按钮来更改我的 CSS 代码中的 background-color。我尝试过诸如
document.getElementByID("").style.background = colour。这不起作用,大概是因为我选择的是 HTML 元素而不是存储 CSS 信息的 ID。我也试过 jQuery。
我试过$("#traffic_light").css("background-color", "green")。
这也不起作用,但可能是因为我在开始时没有使用正确的选择器。如果有人知道为 ID 选择 CSS 样式的选择器,请告诉我。无论如何,这是我的代码:
<!DOCTYPE html>
<html>
<head>
<title>Traffic Lights</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
</head>
<body>
<style type="text/css">
#traffic_light {
width:200px;
height:200px;
padding:10px 11px;
margin:0 auto;
border:2px solid #a1a1a1;
border-radius:150px;
background-color:green;
}
</style>
<div id="traffic_light"></div>
<button type="button" onclick="colour_change()">Change Lights</button>
<script>
var colour = ["green", "orange", "red"];
var i = 0;
document.getElementByID("traffic_light").style.background = colour[i];
function colour_change() {
i++;
document.getElementByID("traffic_light").style.background = colour[i];
};
</script>
</body>
</html>
【问题讨论】:
-
你应该使用
.background而不是.backgroundColor。 -
这只是一个错字。是
getElementById(小写d),不是getElementByID;资本化问题。 Web 开发的第一条规则:始终在控制台中查找错误。 “这不起作用,大概是因为我选择的是 HTML 元素而不是 ID” 不,您选择的是元素,而不是它的 ID。 -
有一个错字。 getElementById 与 getElementByID Demo 不同
标签: javascript jquery html css styles