DIV CSS 佈局教程網

用 JS 讀取圖片的 alt 替代文字
編輯:關於JavaScript     

alt 屬性存放圖片的替代文字,在圖片無法載入時顯示,也是螢幕閱讀器唸給視障使用者聽的內容。讀取它只需存取同名屬性。

 <!DOCTYPE html>
<html>
<body>
<img id="compman" src="compman.gif" alt="Crazy computerman" width="107" height="98">
<p>The value of the alt attribute is:
<script>
 document.write(document.getElementById("compman").alt);
</script>
</p>
</body>
</html>

alt 讀取行為的兩種情況

 var img = document.getElementById("compman");

 img.alt;                    // "Crazy computerman"
 img.getAttribute('alt');    // "Crazy computerman"

 // 若 HTML 上完全沒有 alt 屬性
 noAltImg.alt;               // ""(空字串)
 noAltImg.getAttribute('alt'); // null

這裡有個實務上很重要的差異:img.alt 在未設定時回傳空字串,而 getAttribute 回傳 null。因此要判斷「有沒有寫 alt」,必須用 getAttribute:

 document.querySelectorAll('img').forEach(function(img) {
   if (img.getAttribute('alt') === null) {
     console.warn('缺少 alt:', img.src);
   }
 });

alt 該怎麼寫

alt 不是註解欄位,而是「如果這張圖不能用,你該知道什麼」。判斷方式很簡單:想像你把圖片拿掉,頁面上還需要留什麼字才能讓意思完整?

· 內容圖(照片、圖表、示意圖)→ 描述圖片傳達的資訊。alt="2026 年第一季各區營收比較,北部成長 12%"
· 純裝飾圖(分隔線、背景紋理)→ 留空 alt="",讓螢幕閱讀器跳過。
· 功能圖(icon 按鈕)→ 描述功能而非外觀。alt="關閉視窗" 而非 alt="紅色叉叉"

最糟的寫法是 alt="圖片"、alt="image" 或把檔名塞進去——這對使用者毫無資訊量。也避免在 alt 中塞關鍵詞作弊,那同樣會傷害使用體驗。

動態修改 alt

 var img = document.getElementById("compman");

 img.alt = "更新後的描述文字";   // 直接指派即可,畫面上的替代文字會同步改變

 // 圖表類圖片可提供長描述
 img.setAttribute('aria-describedby', 'chart-desc');
 // 並在頁面中加入 <p id="chart-desc" class="sr-only">...</p>

最後提醒:範例中的 document.write 在文件載入完成後呼叫會清空整個頁面,除錯時請改用 console.log,要在畫面呈現則用 textContent。另外,alt 與 title 常被混用——title 顯示的是滑鼠懸停提示,不能取代 alt,兩者用途不同。

XML學習教程| jQuery入門知識| AJAX入門| Dreamweaver教程| Fireworks入門知識| SEO技巧| SEO優化集錦|
Copyright © DIV+CSS佈局教程網 All Rights Reserved