在許多圖片展示或商品頁面上,我們常會看到「滑鼠移入縮圖即顯示大圖」的效果。這種互動能提升使用者體驗,而實作起來其實並不複雜。以下示範完整的 JS 代碼。
<script type="text/javascript">
//顯示圖片
function over(imgid, obj, imgbig) {
//大圖顯示的最大尺寸 4比3的大小 400 300
maxwidth = 400;
maxheight = 300;
//顯示
obj.style.display = "";
imgbig.src = imgid.src;
//1、寬和高都超過了,看誰超過的多,誰超的多就將誰設置為最大值
//2、如果寬超過了並且高沒有超,設置寬為最大值
//3、如果寬沒超過並且高超過了,設置高為最大值
if (img.width > maxwidth && img.height > maxheight) {
pare = (img.width - maxwidth) - (img.height - maxheight);
if (pare >= 0)
img.width = maxwidth;
else
img.height = maxheight;
}
else if (img.width > maxwidth && img.height <= maxheight) {
img.width = maxwidth;
}
else if (img.width <= maxwidth && img.height > maxheight) {
img.height = maxheight;
}
}
//隱藏圖片
function out() {
document.getElementById('divImage').style.display = "none";
}
</script>
<img id="img" src="https://www.jb51.net/images/logo.gif"
onmouseover="over(img,divImage,imgbig);" onmouseout="out()"
width="100" height="100" alt="" />
<%--顯示大圖標的區域--%>
<div id="divImage" style="display: none; left: 120px;top:5px; position: absolute">
<img id="imgbig" src="https://www.jb51.net/images/logo.gif" alt="預覽" />
</div>
這段代碼的核心邏輯是:當滑鼠移入縮圖時觸發 over 函數顯示大圖並依最大尺寸限制進行縮放,移出時則透過 out 函數將大圖區域隱藏,兼顧了顯示效果與版面整潔。