萬盛學電腦網

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

CSS 實現滑鼠懸停圖片顯示邊框效果 (純 CSS + 選用 JS)

純 CSS 方案 (推薦)

利用相對定位容器 + 絕對定位邊框層,配合 :hover 顯示。

HTML

<div class="con">
  <img src="photo.jpg" alt="示例圖片" width="300" height="200">
  <div class="border"></div>
</div>

CSS

.con {
  position: relative;
  display: inline-block; /* 包裹圖片尺寸 */
  margin: 50px;
}

.border {
  position: absolute;
  top: 0; left: 0; right: 0; bottom: 0;
  border: 5px solid transparent; /* 預留空間防止跳動 */
  pointer-events: none;          /* 讓滑鼠事件穿透到圖片 */
  transition: border-color 0.3s;
}

.con:hover .border {
  border-color: #000;            /* 實線 */
  /* border-style: dashed; */    /* 虛線只需改這行 */
}

JS 輔助方案 (自動適應圖片尺寸)

若圖片尺寸不固定,可用 JS 動態設定容器與邊框層大小:

$(function() {
  var $img = $('img');
  var w = $img.width(), h = $img.height();
  $('.con').css({width: w, height: h});
  $('.border').css({width: w - 10, height: h - 10}); // 扣除 border 寬度*2
});

關鍵點總結

  • 圖片必須設定 width/height 或由 JS 讀取,否則容器無法正確包裹。
  • pointer-events: none 讓邊框層不攔截 hover 事件。
  • transition 增加平滑動畫。
  • 虛線/實線只需切換 border-style。
  • 現代瀏覽器皆支援;IE9+ 完整支援,IE8 需確保 pointer-events 替代方案。
copyright © 萬盛學電腦網 all rights reserved