DIV CSS 佈局教程網

用 JS 為圖片動態加上邊框
編輯:關於JavaScript     

幫圖片加框只需要設定 border 屬性。這個示範把邊框設為 2 像素。

 <!DOCTYPE html>
<html>
<head>
<script>
function addBorder() {
  document.getElementById("compman").border = "2";
}
</script>
</head>
<body>
<img id="compman" src="compman.gif" alt="Computerman" width="107" height="98">
<br><br>
<input type="button" onclick="addBorder()" value="Add border" />
</body>
</html>

border 屬性已被棄用

img 的 border 屬性屬於 HTML 早期的呈現屬性,HTML5 已將它標記為不建議使用。此外它只能設定粗細,無法指定顏色與線條樣式,實用性相當有限。

改用 CSS border

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

 img.style.border = "2px solid #333";   // 粗細 + 樣式 + 顏色

或更推薦 class 切換:

 /* CSS */
img.framed {
  border: 2px solid #333;
  border-radius: 4px;      /* 圓角 */
  box-shadow: 0 1px 4px rgba(0,0,0,.15);  /* 陰影 */
}

/* JS */
document.getElementById("compman").classList.add('framed');

box-sizing 會影響最終尺寸

這是最容易忽略的一點。在預設的 content-box 模式下,加 border 會讓元素整體尺寸變大:

 // 寬 107 + 左右各 2px border = 實際佔據 111px
 img.style.border = "2px solid #333";

 // 若希望維持 107px 不變,讓 border 向內吃
 img.style.boxSizing = "border-box";
 // CSS: img { box-sizing: border-box; }

在 RWD 版面中,box-sizing: border-box 幾乎是必備的全域設定,否則一加上 border 或 padding,元素就會超出容器。

幾個實用的邊框變化

 /* 只加在指定側 */
img.style.borderBottom = "3px solid #e55";

 /* 虛線框 */
img.style.border = "2px dashed #999";

 /* 用 outline 加框而不影響版面(不佔空間、不撐大元素) */
img.style.outline = "2px solid #333";
img.style.outlineOffset = "4px";   /* 框線與圖片間的距離 */

outline 是個好選擇。它不佔用版面空間,不會推開周圍元素,也不受 box-sizing 影響。做 hover 高亮效果時特別好用:

 /* CSS */
img.hoverable:hover { outline: 2px solid #09f; outline-offset: 2px; }

唯一要注意的是:只要設定了 outline,就應該同時處理 :focus 狀態,以維持鍵盤使用者的可見焦點提示,不要為了美觀而移除焦點框。

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