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

แอตทริบิวต์ href ของ <base>: กำหนด Base URL สำหรับ Relative Links ทั้งหมด

แอตทริบิวต์ href ของ <base> คืออะไร?

แอตทริบิวต์ href ของแท็ก <base> ใช้สำหรับ กำหนด Base URL (URL พื้นฐาน) สำหรับ Relative URL ทั้งหมดในหน้าเว็บ** เช่น ลิงก์ รูปภาพ สคริปท์ สไตล์ชีต เป็นต้น

ไวยากรณ์ (Syntax)

<base href="absolute_URL">

ตัวอย่างการใช้งาน

<!DOCTYPE html>
<html>
<head>
  <base href="https://www.example.com/tutorials/">
</head>
<body>
  <h2>รายการบทเรียน</h2>
  <p><a href="java.html">Java Tutorial</a></p>
  <p>(จะทำงานเป็น https://www.example.com/tutorials/java.html)</p>
  <p><a href="jquery.html">jQuery Tutorial</a></p>
  <p>(จะทำงานเป็น https://www.example.com/tutorials/jquery.html)</p>
  <p><img src="logo.png" alt="Logo"></p>
  <p>(จะโหลดจาก https://www.example.com/tutorials/logo.png)</p>
</body>
</html>

การทำงาน

Relative URL ทั้งหมดในหน้า (href, src, action, ฯลฯ) จะถูก Resolve ต่อจาก Base URL:

  • java.html → https://www.example.com/tutorials/java.html
  • jquery.html → https://www.example.com/tutorials/jquery.html
  • logo.png → https://www.example.com/tutorials/logo.png
  • ../index.html → https://www.example.com/index.html (รองรับ relative path)

ข้อควรระวัง

  • <base> ต้องอยู่ใน <head> และมีได้ **เพียง 1 ตัวต่อหน้า**
  • ต้องมี href หรือ target (หรือทั้งคู่) อย่างน้อย 1 ตัว
  • Anchor links (#section) ไม่ได้รับผลกระทบจาก base href
  • Absolute URL (ขึ้นต้น https:// หรือ https://) ไม่ได้รับผลกระทบ
  • วาง <base> ก่อน <link>, <script> ที่ใช้ relative URL

ร่วมกับ target

<base href="https://example.com/" target="_blank">
<!-- ลิงก์ทุกตัวจะเปิดในแท็บใหม่ โดยอัตโนมัติ -->