通过 JavaScript 在 HTML 中添加类(奇数和偶数)?
javascriptweb developmentobject oriented programming更新于 2025/8/19 9:48:17
要添加类,请使用 nth-child(odd) 和 nth-child(even)。以下是代码 −
示例
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
</head>
<body>
<section class="subjects">
<article class="subjectName ">MongoDB</article>
<article class="subjectName ">Javascript</article>
<article class="subjectName ">Java</article>
<article class="subjectName ">MySQL</article>
</section>
<style>
.subjectName:nth-child(odd) {
color: blue;
}
.subjectName:nth-child(even) {
color: purple;
}
</style>
</body>
</html>
要运行上述程序,请保存文件名anyName.html(index.html),然后右键单击该文件并选择在 VS 代码编辑器中使用实时服务器打开选项。
输出

相关文章
有用资源
javascript 参考教程 - 该教程包含有关 javascript 的更多信息:https://www.cainiaomax.com/javascript/

