ใช้แท็ก <a> (Anchor) เพื่อสร้างไฮเปอร์ลิงก์ใน HTML แท็ก <a> ใช้สำหรับสร้างลิงก์ไปยังเอกสารอื่น หรือตำแหน่งภายในเอกสารปัจจุบัน
แอตทริบิวต์หลักของแท็ก <a>
| แอตทริบิวต์ | ค่า | คำอธิบาย |
|---|---|---|
href |
URL | จำเป็น - ระบุ URL ของหน้าหรือชื่อ Anchor ที่ลิงก์ไป |
target |
_blank, _self, _parent, _top, framename | ระบุที่เปิดลิงก์: _blank=แท็บใหม่, _self=กรอบเดียวกัน (ค่าเริ่มต้น), _parent=เฟรมพาเรนต์, _top=หน้าต่างเต็ม |
download |
filename | ดาวน์โหลดเป้าหมายเมื่อผู้ใช้คลิก (HTML5) |
rel |
noopener, noreferrer, nofollow, etc. | ระบุความสัมพันธ์กับเอกสารปลายทาง สำคัญสำหรับความปลอดภัย |
hreflang |
language_code | รหัสภาษาของ URL ปลายทาง |
type |
MIME_type | ระบุประเภท MIME ของ URL ปลายทาง |
name |
section_name | Deprecated ใน HTML5 - ใช้ id แทนสำหรับ Anchor ภายในหน้า |
charset |
character_encoding | Deprecated - การเข้ารหัสตัวอักษรของเอกสารลิงก์ |
coords, shape |
coordinates | Deprecated - ใช้สำหรับ Image Map (ร่วมกับ <map>) |
rev |
link types | Deprecated - ความสัมพันธ์ย้อนกลับ |
ตัวอย่างพื้นฐาน
<!DOCTYPE html>
<html>
<head>
<title>HTML a Tag</title>
</head>
<body>
<p>Welcome to <a href="https://www.example.com">Example</a></p>
</body>
</html>
ตัวอย่างการใช้งานแอตทริบิวต์สำคัญ
1. เปิดในแท็บใหม่ (ปลอดภัย)
<a href="https://example.com" target="_blank" rel="noopener noreferrer">
Open in new tab</a>
rel="noopener noreferrer" ป้องกันปัญหาความปลอดภัย (tabnabbing) และไม่ส่ง Referrer
2. ดาวน์โหลดไฟล์
<a href="/files/report.pdf" download="annual-report-2024.pdf">
Download Report</a>
3. Anchor ภายในหน้าเดียวกัน (Fragment URL)
<!-- ลิงก์ไปยังส่วนในหน้าเดียวกัน -->
<a href="#section2">Go to Section 2</a>
<!-- ส่วนปลายทาง (ใช้ id แทน name) -->
<h2 id="section2">Section 2</h2>
4. ลิงก์อีเมลและโทรศัพท์
<a href="mailto:contact@example.com?subject=Inquiry">Email Us</a>
<a href="tel:+6621234567">Call Us</a>
5. rel attribute ค่าที่สำคัญ
| ค่า rel | วัตถุประสงค์ |
|---|---|
noopener |
ป้องกันหน้าใหม่เข้าถึง window.opener (ความปลอดภัย) |
noreferrer |
ไม่ส่ง HTTP Referrer header |
nofollow |
บอก Search Engine ไม่ต้องติดตามลิงก์นี้ (SEO) |
external |
บ่งชี้เป็นลิงก์ภายนอก |
author |
ลิงก์ไปหน้าผู้เขียน |
แนวทางปฏิบัติที่ดีที่สุด
- ข้อความลิงก์ควรอธิบายได้ด้วยตัวเอง (หลีกเลี่ยง "คลิกที่นี่")
- ใช้
rel="noopener noreferrer"เสมอเมื่อtarget="_blank" - ใช้
idแทนnameสำหรับ Anchor ภายในหน้า - เพิ่ม
titleattribute สำหรับ tooltip เพิ่มเติม (ถ้าจำเป็น)