透過 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.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 程式碼編輯器中選擇使用即時伺服器開啟的選項。

輸出

更新時間:2020 年 7 月 16 日

543 次瀏覽

開啟您的 職業

透過完成課程獲得認證

立即開始
廣告
© . All rights reserved.