Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> HTML

แอตทริบิวต์ HTML (HTML Attributes)

แอตทริบิวต์ (Attributes) ใช้สำหรับกำหนดคุณสมบัติให้ element เช่น ความกว้าง/สูงของรูปภาพหรือ canvas ทุก element สามารถมี attribute ได้ และให้ข้อมูลเพิ่มเติม Attribute ประกอบด้วย ชื่อ (name) และ ค่า (value)

ตัวอย่าง

<canvas id="newCanvas" width="400" height="300">
<img alt="alternate text">

เครื่องหมายคำพูด: ตามมาตรฐาน HTML5 ไม่บังคับให้มี quotes รอบค่า attribute แต่ แนะนำให้ใส่เสมอ เพื่อป้องกันข้อผิดพลาดและอ่านง่าย


ตัวอย่างแอตทริบิวต์ต่างๆ

1. แอตทริบิวต์ start ของ <ol>

กำหนดค่าเริ่มต้นของรายการลำดับแรก

ไวยากรณ์: <ol start="num">

<!DOCTYPE html>
<html>
<body>
<h1>ผลการสอบภาคปลาย MCA</h1>
<h2>อันดับ 1-5</h2>
<ol>
  <li>Steve</li> <li>David</li> <li>Kane</li> <li>William</li> <li>John</li>
</ol>
<h2>อันดับ 5-10</h2>
<ol start="5">
  <li>Tom</li> <li>Jack</li> <li>Will</li> <li>Harry</li> <li>Tim</li>
</ol>
</body>
</html>

ผลลัพธ์: รายการแรกเริ่มที่ 1, รายการที่สองเริ่มที่ 5


2. แอตทริบิวต์ autofocus ของ <textarea>

ตั้งค่าให้ textarea ได้รับโฟกัสอัตโนมัติเมื่อโหลดหน้า (เพิ่มใน HTML5)

ไวยากรณ์: <textarea autofocus>

<!DOCTYPE html>
<html>
<body>
<h2>คำถามสัมภาษณ์</h2>
<p>ทำไมคุณจึงอยากเป็น Technical Writer? (100 คำ)</p>
<textarea rows="6" cols="70" autofocus> เขียนคำตอบใน 100 คำ... </textarea>
<p>จุดแข็งของคุณคืออะไร? (50 คำ)</p>
<textarea rows="4" cols="70" autofocus> เขียนคำตอบใน 50 คำ... </textarea>
</body>
</html>

ผลลัพธ์: Textarea แรกจะได้รับโฟกัสเมื่อโหลดหน้า (textarea ที่สองก็มี autofocus แต่เบราว์เซอร์จะเลือกตัวแรก)


แอตทริบิวต์สำคัญอื่นๆ ที่ควรรู้จัก

แอตทริบิวต์ใช้กับคำอธิบาย
idทุก elementตัวระบุเอกลักษณ์ (unique)
classทุก elementกลุ่ม element (ซ้ำได้)
styleทุก elementInline CSS
titleทุก elementTooltip/คำอธิบายเพิ่มเติม
hiddenทุก elementซ่อน element (boolean)
data-*ทุก elementCustom data attributes
srcimg, video, audio, iframe, scriptแหล่งที่มาของไฟล์
altimg, area, inputข้อความทางเลือก (accessibility)
hrefa, link, areaURL ปลายทาง
typeinput, button, script, styleประเภทของ element
nameform elementsชื่อสำหรับ form submission
valueinput, option, button, etc.ค่าของ element
placeholderinput, textareaข้อความแนะนำ
requiredform inputsบังคับกรอก
disabledform elementsปิดใช้งาน
readonlyinput, textareaอ่านอย่างเดียว

Global Attributes: id, class, style, title, hidden, data-*, tabindex, accesskey, contenteditable, dir, lang, spellcheck, translate — ใช้กับทุก element ได้