我需要在行中有不同颜色的div。div上的交替背景颜色
我试图在普通浏览器中工作,然后尝试在后端/前端实现它。所以这里是我的测试代码。我不能为了我的生活找出为什么这不起作用。我已经尝试了与身体onload而不是在脚本标记,我已经尝试链接到外部jS。我想到了一个示例代码,这将是最简单的方法。
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title></title>
<meta name="description" content="HTML5">
<meta name="author" content="Site">
<style>
.testclass {
width: 100%;
height: 10px;
background-color: #fdc345;
}
</style>
</head>
<body>
<div class="testclass"></div>
<div class="testclass"></div>
<div class="testclass"></div>
<div class="testclass"></div>
<script>
function isEven(value) {
if (value % 2 == 0) {
return true;
} else {
return false;
}
}
function setColors() {
var userList = document.getElementsByClassName("testclass");
var i;
for (i = 0 i < userList.length; i++) {
if (isEven(i) == true) {
userList[i].style["background-color"] = "red";
/* I also tried document.getElementsByClassName("testclass")[i].style.backgroundColor = "red" */
} else {
userList[i].style["background-color"] = "blue";
}
}
}
window.onload = setColors;
</script>
</body>
</html>
缺少什么我在这里?
_“我缺少的是在这里吗?” _ - 他们正确的思想中没有人再使用JS,因为CSS为您提供了解决这个问题所需的所有工具。 https://developer.mozilla.org/en/docs/Web/CSS/:nth-child – CBroe
您的for循环是否丢失了分号或它只是复制粘贴错误? –
感谢这个CBroe,这实际上可以解决我们的问题,而且非常简单。 –