คุณสมบัติคลาส HTML
ตัวอย่าง
การใช้แอตทริบิวต์ class ในเอกสาร HTML:
<html>
<head>
<style>
h1.intro {
color: blue;
}
p.important {
color: green;
}
</style>
</head>
<body>
<h1 class="intro">Header 1</h1>
<p>A paragraph.</p>
<p class="important">Note that this is an important paragraph. :)</p>
</body>
</html>
ตัวอย่าง "ลองใช้เอง" เพิ่มเติมด้านล่าง
ความหมายและการใช้งาน
แอตทริบิวต์class
ระบุชื่อคลาสอย่างน้อยหนึ่งชื่อสำหรับองค์ประกอบ
แอตทริบิวต์ ส่วนclass
ใหญ่จะใช้เพื่อชี้ไปที่คลาสในสไตล์ชีต อย่างไรก็ตาม JavaScript สามารถใช้ (ผ่าน HTML DOM) เพื่อทำการเปลี่ยนแปลงองค์ประกอบ HTML ด้วยคลาสที่ระบุได้
รองรับเบราว์เซอร์
Attribute | |||||
---|---|---|---|---|---|
class | Yes | Yes | Yes | Yes | Yes |
ไวยากรณ์
<element class="classname">
ค่าแอตทริบิวต์
Value | Description |
---|---|
classname | Specifies one or more class names for an element. To specify multiple classes, separate the class names with a space, e.g. <span class="left important">. This allows you to combine several CSS classes for one HTML element.
Naming rules:
|
ตัวอย่างเพิ่มเติม
ตัวอย่าง
เพิ่มหลายคลาสให้กับองค์ประกอบ HTML เดียว:
<!DOCTYPE html>
<html>
<head>
<style>
h1.intro {
color: blue;
text-align: center;
}
.important {
background-color: yellow;
}
</style>
</head>
<body>
<h1 class="intro important">Header 1</h1>
<p>A paragraph.</p>
</body>
</html>
ตัวอย่าง
การใช้ JavaScript เพื่อเพิ่มสีพื้นหลังสีเหลืองให้กับองค์ประกอบแรกด้วย class="example" (ดัชนี 0)
var x = document.getElementsByClassName("example");
x[0].style.backgroundColor = "yellow";
ตัวอย่าง
การใช้ JavaScript เพื่อเพิ่มคลาส "mystyle" ให้กับองค์ประกอบด้วย id="myDIV":
document.getElementById("myDIV").classList.add("mystyle");
หน้าที่เกี่ยวข้อง
บทช่วยสอน HTML: แอตทริบิวต์ HTML
บทช่วยสอน CSS: ไวยากรณ์ CSS
การอ้างอิง CSS: CSS .class Selector
การอ้างอิง HTML DOM: HTML DOM getElementsByClassName() Method
การอ้างอิง HTML DOM: คุณสมบัติ HTML DOM className
การอ้างอิง HTML DOM: HTML DOM classList Property
การอ้างอิง HTML DOM: HTML DOM Style Object