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

廣告
資料結構
網路
RDBMS
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP