做一個「滑過縮圖就放大」的效果不難,難的是把各種邊界情況都處理好:圖片在本機還是遠端、原圖太小、載入失敗、Firefox 重複請求圖片……本文記錄這個放大外掛從結構設計到細節修正的完整過程。
<div class="imgMagnifierWrap">
<div class="overlay"></div> <!-- 覆蓋層,滑鼠感應區域,疊在小圖最上層 -->
<div class="tipboxHover"></div> <!-- 小圖上方的懸停提示方框 -->
<div class="imgOriginal"> <!-- 承載大圖的容器,絕對定位 -->
<img src="bigOne.jpg" /> <!-- 前景大圖,絕對定位 -->
</div>
</div>
<style type="text/css">
.imgMagnifierWrap * { position: absolute; background: #fff; }
.imgMagnifierWrap .tipboxHover {
width: 80px; height: 60px;
filter: alpha(opacity=30); opacity: .3;
display: none;
}
.imgMagnifierWrap .imgOriginal {
display: none; z-index: 9999; overflow: hidden;
width: 400px; height: 400px;
background-color: #cdf; background-repeat: no-repeat;
text-align: center; border: 1px solid #555;
}
.imgMagnifierWrap .overlay {
cursor: crosshair;
filter: alpha(opacity=0); opacity: 0;
}
</style>
為了知道大圖何時就緒,先寫一個通用的預載函式,同時支援 load 與自訂的 begin 事件:
$.imgPreloader = function (url, eventLists) {
var img = new Image();
var $img = $(img);
img.src = url;
$.each(eventLists, function (type, fn) { $img.bind(type, fn); });
$img.trigger(img.complete ? 'load' : 'begin');
return $img;
};
小圖的四邊各要扣掉指示方框一半的寬高,才是有效的滑鼠對應範圍;超出這個範圍時,大圖就停在邊界不再移動。
var borderLeft = thumbInfo.left + tipboxInfo.width / 2; var ratioX = (mouseInfo.x - borderLeft) / (thumbInfo.width - tipboxInfo.width);
最初的做法是用隱藏的前景圖片預載,並在 load 事件裡判斷時機。結果 IE 與 Chrome 一切正常,Firefox 卻會請求兩次圖片,而且沒有走快取。
換個思路:不預載大圖,改成先在大圖位置放一層「loading」覆蓋層。Chrome 下呈現為漸進式載入,其他瀏覽器則是載完才直接顯示——可用,但總覺得少一點什麼。
把大圖真正放進 DOM 當前景圖片後,最大的好處是 load 與 error 兩個事件都能正常工作,載入失敗也能給使用者明確回饋:
$.imgPreloader($anchor.attr('href'), {
load: function () {
isImageReady = true;
$o.empty().append(this);
setTimeout(autoFitPicture, 0);
},
begin: function () { $o.text('loading...'); },
error: function () {
isImageReady = true;
$o.text('invalid picture!');
}
});
大圖的 load 事件和小圖的 mousemove 事件時機完全不同,硬湊在一起會抖動。解法是把「記座標」與「定位」兩件事拆開:滑鼠移動時只更新座標並呼叫定位函式,指示框的位置永遠跟著滑鼠,大圖位置則依目前是否就緒來決定。
// 滑鼠位置暫存
var mouseInfo = { x: 0, y: 0 };
// 指示框定位
var setTipboxPosition = function (e) {
mouseInfo.x = e.pageX;
mouseInfo.y = e.pageY;
$tipbox.css({
top: mouseInfo.y < thumbInfo.width / 2 + thumbInfo.top
? Math.max(mouseInfo.y - tipboxInfo.height / 2, thumbInfo.top)
: Math.min(mouseInfo.y - tipboxInfo.height / 2,
thumbInfo.top + thumbInfo.height - tipboxInfo.height),
left: mouseInfo.x < thumbInfo.width / 2 + thumbInfo.left
? Math.max(mouseInfo.x - tipboxInfo.width / 2, thumbInfo.left)
: Math.min(mouseInfo.x - tipboxInfo.width / 2,
thumbInfo.left + thumbInfo.width - tipboxInfo.width)
});
setImgPosition();
};
順帶一提,如果使用的瀏覽器夠幸運,某些跨browser 的細節會省下不少力氣。
展示程式碼與打包下載:https://www.jb51.net/jiaoben/22866.html