做一個能用滾輪縮放、還能拖著跑的圖片檢視器,是不少圖廊網站的需求。本文先給一個不用 jQuery 的純縮放版本,再示範用 jQuery 實作縮放加拖動的完整功能。
透過 onmousewheel 事件與 event.wheelDelta 判斷滾輪方向,改變圖片的 zoom 值:
var count = 10;
function Picture() {
count = Counting(count);
Resize(count);
return false;
}
function Counting(count){
if (event.wheelDelta >= 120) count++;
else if (event.wheelDelta <= -120) count--;
return count;
}
function Resize(count){
oImage.style.zoom = count + '0%';
oCounter.innerText = count + '0%';
}
用 jQuery 版時,先判斷瀏覽器用 DOMMouseScroll 還是 mousewheel 事件,綁定後依滾輪方向改變圖片尺寸與位置:
$(function () {
var event = $.browser.mozilla ? "DOMMouseScroll" : "mousewheel";
$("#divBlock").bind(event, function (e) {
var evt = window.event || e;
var newWidth, newHeight, newLeft, newTop;
var overHeight = $("#divBlock").height();
if (evt.detail > 0 || evt.wheelDelta < 0) {
newWidth = $("#imgMain").width() - 20;
newHeight = $("#imgMain").height() - 20;
newLeft = $("#imgMain").position().left + 10;
newTop = $("#imgMain").position().top + 10 - overHeight;
} else {
newWidth = $("#imgMain").width() + 20;
newHeight = $("#imgMain").height() + 20;
newLeft = $("#imgMain").position().left - 10;
newTop = $("#imgMain").position().top - 10 - overHeight;
}
$("#imgMain").css({ left: newLeft + "px", top: newTop + "px" });
$("#imgMain").width(newWidth).height(newHeight);
});
拖動則靠 mousedown 記下起始游標與圖片位置,在 mousemove 中依位移更新圖片座標,並在 mouseup/mouseout 時解除 mousemove 綁定。這種「透明覆蓋層接收事件」的做法能避免拖曳時選取到文字,是實作圖片拖曳常見的技巧。