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

คุณสมบัติ href ของ Link ใน HTML DOM

คุณสมบัติ href ของอีลีเมนต์ <link> ใช้ตั้งค่าหรืออ่านพาธ/URL ของเอกสารที่ลิงก์ไป

ไวยากรณ์ (Syntax)

การอ่านค่า

linkObject.href

การตั้งค่า

linkObject.href = string

ค่าที่เป็นไปได้

ประเภทรายละเอียด
pathพาธแบบ absolute หรือ relative ไปยังเอกสาร
urlURL เต็มของเอกสารที่ลิงก์

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

ตัวอย่างด้านล่างเปลี่ยน stylesheet จาก style.css เป็น anotherStyle.css:

<!DOCTYPE html>
<html>
<head>
<title>Link href</title>
<link id="extStyle" rel="stylesheet" type="text/css" href="style.css">
</head>
<body>
<form>
  <fieldset>
    <legend>Link-href</legend>
    <label for="WeekSelect">Sales Target Week: <input type="week" id="WeekSelect" value="2020-W13" disabled> </label>
    <input type="button" onclick="enableWeekInput()" value="Change Sales Target Week">
    <input type="button" onclick="changeStyle()" value="Change Style">
    <div id="divDisplay"></div>
  </fieldset>
</form>
<script>
  var divDisplay = document.getElementById("divDisplay");
  var inputWeek = document.getElementById("WeekSelect");
  var extStyle = document.getElementById("extStyle");
  divDisplay.textContent = 'Week Input disabled: ' + inputWeek.disabled;
  
  function enableWeekInput() {
    inputWeek.disabled = false;
    divDisplay.textContent = 'Week Input disabled: ' + inputWeek.disabled;
  }
  
  function changeStyle() {
    extStyle.href = 'anotherStyle.css';
  }
</script>
</body>
</html>

ในตัวอย่าง style.css:

form { width:70%; margin: 0 auto; text-align: center; }
* { padding: 2px; margin:5px; }
input[type="button"] { border-radius: 10px; }

ในตัวอย่าง anotherStyle.css:

form { width:70%; margin: 0 auto; text-align: center; background-color: rgba(0,0,0,0.7); color: white; }
* { padding: 2px; margin:5px; }
input[type="button"] { border-radius: 10px; }

ผลลัพธ์

ก่อนคลิกปุ่ม "Change Style": ใช้ style.css (พื้นหลังสีขาว)

หลังคลิกปุ่ม "Change Style": ใช้ anotherStyle.css (พื้นหลังสีดำ ตัวอักษรสีขาว)

หมายเหตุ: รูปภาพตัวอย่างจากต้นฉบับไม่ได้รวมอยู่ในเนื้อหานี้