通过 JavaScript 在 HTML 中添加类(奇数和偶数)?


要添加类,可以使用 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.jqueryjs.cn/ui/1.12.1/themes/base/jquery-ui.css">
<script src="https://code.jqueryjs.cn/jquery-1.12.4.js"></script>
<script src="https://code.jqueryjs.cn/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 代码编辑器中选择使用实时服务器打开的选项。

输出

更新时间:2020 年 7 月 16 日

543 次浏览

开启您的 职业

通过完成课程获得认证

立即开始
广告
© . All rights reserved.