萬盛學電腦網

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

HTML 超連結實作範例:相對路徑、錨點與導航最佳實務

HTML 超連結 (a 標籤) 實作完整範例與最佳實務

超連結是網頁互聯的核心。本文透過實際代碼範例,示範相對路徑導航、頁內錨點跳轉、新分頁開啟與無障礙屬性設定。

基本超連結範例

<!DOCTYPE html>
<html lang="zh-Hant">
<head>
  <meta charset="UTF-8">
  <title>超連結示範頁面</title>
</head>
<body>
  <h1>歡迎來到首頁</h1>
  <p><a href="about.html">關於我們</a></p>
  <p><a href="products/list.html">產品列表</a></p>
  <p><a href="https://partner.example.com" target="_blank" rel="noopener noreferrer">合作夥伴網站 (新分頁)</a></p>
  <p><a href="mailto:support@example.com?subject=詢問">聯繫客服</a></p>
</body>
</html>

相對路徑優於絕對路徑的理由

  • 可攜性:網站遷移域名或測試環境無需修改連結。
  • 維護性:目錄結構調整時,僅需更新相對路徑。
  • 效能:瀏覽器解析相對路徑較快 (無 DNS 查詢)。

目錄結構與路徑對照

專案根目錄/
├── index.html          ← 目前頁面
├── about.html          ← 同層:href="about.html"
├── products/
│   ├── list.html       ← 子目錄:href="products/list.html"
│   └── detail.html
└── assets/
    └── style.css

進階技巧:頁內錨點與平滑滾動

<!-- 導覽列 -->
<nav>
  <a href="#features">功能特色</a> |
  <a href="#pricing">方案價格</a> |
  <a href="#contact">聯繫我們</a>
</nav>

<!-- 內容區塊 -->
<section id="features">...</section>
<section id="pricing">...</section>
<section id="contact">...</section>

<!-- CSS 平滑滾動 (現代瀏覽器支援) -->
<style> html { scroll-behavior: smooth; } </style>

無障礙與 SEO 關鍵屬性

  • rel="noopener noreferrer":target="_blank" 時必加,防止反向存取。
  • aria-label:連結文字無語意時 (如純圖示) 提供語意。
  • title:滑鼠懸停提示補充說明 (非必要)。
  • 連結文字應具描述性,避免「點這裡」、「更多」。

掌握超連結細節,打造流暢、安全、可存取的導航體驗。

copyright © 萬盛學電腦網 all rights reserved