利用相對定位容器 + 絕對定位邊框層,配合 :hover 顯示。
<div class="con">
<img src="photo.jpg" alt="示例圖片" width="300" height="200">
<div class="border"></div>
</div>
.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 動態設定容器與邊框層大小:
$(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
});
pointer-events: none 讓邊框層不攔截 hover 事件。transition 增加平滑動畫。border-style。pointer-events 替代方案。