萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網頁製作 >> HTML5 教學

HTML5 錨點語法更新:改用 id 屬性取代 name

HTML5 規範已移除 name 屬性對錨點的支援,現行標準統一使用 id 屬性來定義頁面內部跳轉目標。這不僅簡化了語法,也提升了語意清晰度。

基本用法

在目標元素加上 id,再以 href="#id值" 建立連結:

<div id="section1">目標區塊</div>
<a href="#section1">跳轉至 Section 1</a>

完整範例

下列代碼示範頁首與頁尾互相跳轉,並包含多個彩色區塊模擬長頁面:

<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <title>HTML5 錨點示範</title>
  <style> body { margin: 0; } </style>
</head>
<body>
  <div id="pageTop"><a href="https://example.com">網站首頁</a> | <a href="#pageBottom">直達頁尾</a></div>
  <div style="height: 30px; text-align: center;"><a href="#pageBottom">↓ 捲動到底部 ↓</a></div>
  <div style="background:#959822; height:150px;">內容區 1</div>
  <div style="background:green; height:150px;">內容區 2</div>
  <div style="background:red; height:150px;">內容區 3</div>
  <div style="background:yellow; height:150px;">內容區 4</div>
  <div style="background:silver; height:150px;">內容區 5</div>
  <div style="background:aqua; height:150px;">內容區 6</div>
  <div style="background:fuchsia; height:150px;">內容區 7</div>
  <div style="background:green; height:150px;">內容區 8</div>
  <div style="background:blue; height:150px;">內容區 9</div>
  <div style="background:olive; height:150px;">內容區 10</div>
  <div id="pageBottom" style="height:276px; background:url('https://example.com/footer.jpg') center top no-repeat; text-align:center;">
    <a href="#pageTop">↑ 回到頂部 ↑</a>
  </div>
</body>
</html>

瀏覽器支援

Chrome、Firefox、Safari、Edge 及 IE8 以上版本皆完整支援。若需相容極舊瀏覽器,可同時保留 name 與 id,但現代開發建議僅使用 id。

直接連結範例

外部連結可直接指向錨點:https://example.com/page.html#pageBottom,載入後瀏覽器會自動捲動至該位置。

copyright © 萬盛學電腦網 all rights reserved