DIV CSS 佈局教程網

jQuery 圖片縮放與拖動的實作範例(含純 JS 版)
編輯:JQuery特效代碼     

做一個能用滾輪縮放、還能拖著跑的圖片檢視器,是不少圖廊網站的需求。本文先給一個不用 jQuery 的純縮放版本,再示範用 jQuery 實作縮放加拖動的完整功能。

純 JavaScript:滾輪縮放

透過 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:縮放 + 拖動

用 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 綁定。這種「透明覆蓋層接收事件」的做法能避免拖曳時選取到文字,是實作圖片拖曳常見的技巧。

XML學習教程| jQuery入門知識| AJAX入門| Dreamweaver教程| Fireworks入門知識| SEO技巧| SEO優化集錦|
Copyright © DIV+CSS佈局教程網 All Rights Reserved