DIV CSS 佈局教程網

用純 JavaScript 打造商品放大鏡效果
編輯:關於JavaScript     

逛過電商網站(如淘寶、京東)的人,對商品詳情頁那種「滑鼠移上去就能放大檢視細節」的放大鏡效果應該不陌生。網路上這類插件琳瑯滿目,但真正套用到專案裡時總有各種不順手,於是我乾脆花點時間自己刻一個,順便累積一些可重複使用的程式碼,何樂而不為呢?咱們開始吧。

我的計畫是先把最核心的算法跑通,再一步步把它封裝成插件。先看最簡單的 HTML 結構:

<div id="Magnifier"></div>

CSS 部分幾乎是空的,先把基本樣式歸零:

<style>
    * {
        margin: 0;
        padding: 0;
    }
</style>

接下來就交給強大的 JavaScript 了。整體結構由幾個部分組成:小圖容器、蓋在小圖上的透明遮罩層(用來接收滑鼠事件)、跟著滑鼠移動的鏡片,以及右側用 overflow 裁切的大圖預覽視窗。核心在於:鏡片在小圖上的相對位置比例,會對應到大圖在預覽窗中的位移比例。

function createElement(MagnifierId, sImg, bImg) {
    var Magnifier = $(MagnifierId);
    Magnifier.style.position = 'relative';
    // 小圖容器
    var smallDiv = $Create("div");
    smallDiv.setAttribute("id", "small");
    smallDiv.style.position = "absolute";
    // 遮罩層
    var mask = $Create("div");
    mask.setAttribute("id", "mask");
    mask.style.position = "absolute";
    // 鏡片
    var mirror = $Create("div");
    mirror.setAttribute("id", "mirror");
    mirror.style.opacity = 0.3;
    mirror.style.position = "absolute";
    mirror.style.display = "none";
    // 小圖
    var smallImg = $Create("img");
    smallImg.setAttribute("src", sImg);
    smallImg.setAttribute("id", "smallImg");
    smallImg.onload = function () {
        // 若未設定放大鏡尺寸,則依小圖大小自動撐開
        if (!Magnifier.offsetHeight) {
            Magnifier.style.width = this.offsetWidth + "px";
            Magnifier.style.height = this.offsetHeight + "px";
        }
        // 遮罩層與小圖等大
        mask.style.opacity = "0";
        mask.style.width = this.width + 'px';
        mask.style.height = this.height + "px";
        mask.style.zIndex = 2;
        bigDiv.style.left = this.width + 5 + "px";
        bigDiv.style.top = "-5px";
    }
    smallDiv.appendChild(mask);
    smallDiv.appendChild(mirror);
    smallDiv.appendChild(smallImg);
    // 預覽視窗
    var bigDiv = $Create("div");
    bigDiv.setAttribute("id", "big");
    bigDiv.style.position = "absolute";
    bigDiv.style.overflow = "hidden";
    bigDiv.style.display = "none";
    var bigImg = $Create("img");
    bigImg.setAttribute("src", bImg);
    bigImg.setAttribute("id", "bigImg");
    bigImg.style.position = "absolute";
    bigDiv.appendChild(bigImg);
    Magnifier.appendChild(smallDiv);
    Magnifier.appendChild(bigDiv);
}

接著是樣式設定與事件綁定。事件部分包含移入顯示、移出隱藏,以及最關鍵的 mousemove:先算出鏡片中心對齊游標的位置並做邊界夾制,再換算成比例去驅動大圖位移。

function setMagnifierStyle(mirrorStyle, shichuangStyle) {
    // 鏡片樣式
    for (var item in mirrorStyle) {
        mirror.style[item] = mirrorStyle[item];
    }
    // 預覽視窗樣式
    for (var item in shichuangStyle) {
        $("big").style[item] = shichuangStyle[item];
    }
}
function registerEvent() {
    $("mask").onmouseover = function () {
        $("big").style.display = "block";
        mirror.style.display = "block";
    }
    $("mask").onmouseout = function () {
        $("big").style.display = "none";
        mirror.style.display = "none";
    }
    $("mask").onmousemove = function (evt) {
        var oEvent = evt || event;
        var disX = oEvent.offsetX;
        var disY = oEvent.offsetY;
        var mirrorLeft = disX - mirror.offsetWidth / 2;
        var mirrorTop = disY - mirror.offsetHeight / 2;
        if (mirrorLeft < 0) {
            mirrorLeft = 0;
        }
        else if (mirrorLeft > mask.offsetWidth - mirror.offsetWidth) {
            mirrorLeft = mask.offsetWidth - mirror.offsetWidth;
        }
        if (mirrorTop < 0) {
            mirrorTop = 0;
        }
        else if (mirrorTop > mask.offsetHeight - mirror.offsetHeight) {
            mirrorTop = mask.offsetHeight - mirror.offsetHeight;
        }
        mirror.style.top = mirrorTop + "px";
        mirror.style.left = mirrorLeft + "px";
        // 依鏡片位置比例,反推大圖位移
        var paX = mirrorTop / (mask.offsetHeight - mirror.offsetHeight);
        var paY = mirrorLeft / (mask.offsetWidth - mirror.offsetWidth);
        $("bigImg").style.top = -paX * ($("bigImg").offsetHeight - $("big").offsetHeight) + "px";
        $("bigImg").style.left = -paY * ($("bigImg").offsetWidth - $("big").offsetWidth) + "px";
    }
}
function $(id) {
    return document.getElementById(id);
}
function $Create(type) {
    return document.createElement(type);
}

最後在 onload 時呼叫一下,效果就出來了:

window.onload = function () {
    createElement("Magnifier", "images/Magnifier/small.jpg", "images/Magnifier/big.jpg");
    setMagnifierStyle({ "width": "30px", "height": "30px", "backgroundColor": "#fff" }, { "width": "250px", "height": "250px" });
    registerEvent();
}

封裝成 Magnifier 類別

能跑之後,接下來把它整理成一個可重複使用的類別。建構函式接收容器 ID、小圖路徑、大圖路徑,以及鏡片與預覽窗的樣式設定(皆為 JSON 格式),並在初始化時依序完成建構、套用樣式與綁定事件:

function Magnifier(
    MagnifierId,   // 放大鏡容器 ID
    sImg,          // 小圖片 src
    bImg,          // 大圖片 src
    mirrorStyle,   // 鏡片樣式,JSON 格式
    ViewStyle      // 預覽視窗樣式,JSON 格式
    ) {
    var _this = this;
    this.MagnifierContainer = null;   // 容器
    this.smallDiv = null;             // 小圖容器
    this.mask = null;                 // 小圖遮罩層
    this.mirror = null;               // 小圖鏡片
    this.smallImg = null;             // 小圖
    this.bigDiv = null;               // 預覽視圖
    this.bigImg = null;               // 大圖
    var init = function () {
        _this.MagnifierContainer = _this.$(MagnifierId);
        _this.createElement(sImg, bImg);
        _this.setMagnifierStyle(mirrorStyle, ViewStyle);
        _this.MainEvent();
    }
    init();
}
Magnifier.prototype.createElement = function (sImg, bImg) {
    var _this = this;
    var $Create = this.$Create;
    this.MagnifierContainer.style.position = 'relative';
    this.smallDiv = $Create("div");
    this.smallDiv.setAttribute("id", "small");
    this.smallDiv.style.position = "absolute";
    this.mask = $Create("div");
    this.mask.setAttribute("id", "mask");
    this.mask.style.position = "absolute";
    this.mirror = $Create("div");
    this.mirror.setAttribute("id", "mirror");
    this.mirror.style.opacity = 0.3;
    this.mirror.style.position = "absolute";
    this.mirror.style.display = "none";
    this.smallImg = $Create("img");
    this.smallImg.setAttribute("src", sImg);
    this.smallImg.setAttribute("id", "smallImg");
    this.smallImg.onload = function () {
        if (!_this.MagnifierContainer.offsetHeight) {
            _this.MagnifierContainer.style.width = this.offsetWidth + "px";
            _this.MagnifierContainer.style.height = this.offsetHeight + "px";
        }
        _this.mask.style.opacity = "0";
        _this.mask.style.width = this.offsetWidth + 'px';
        _this.mask.style.height = this.offsetHeight + "px";
        _this.mask.style.zIndex = 2;
        _this.bigDiv.style.left = this.offsetWidth + 5 + "px";
        _this.bigDiv.style.top = "-5px";
    }
    this.smallDiv.appendChild(this.mask);
    this.smallDiv.appendChild(this.mirror);
    this.smallDiv.appendChild(this.smallImg);
    this.bigDiv = $Create("div");
    this.bigDiv.setAttribute("id", "big");
    this.bigDiv.style.position = "absolute";
    this.bigDiv.style.overflow = "hidden";
    this.bigDiv.style.display = "none";
    this.bigImg = $Create("img");
    this.bigImg.setAttribute("src", bImg);
    this.bigImg.setAttribute("id", "bigImg");
    this.bigImg.style.position = "absolute";
    this.bigDiv.appendChild(this.bigImg);
    this.MagnifierContainer.appendChild(this.smallDiv);
    this.MagnifierContainer.appendChild(this.bigDiv);
}
Magnifier.prototype.setMagnifierStyle = function (mirrorStyle, ViewStyle) {
    for (var item in mirrorStyle) {
        this.mirror.style[item] = mirrorStyle[item];
    }
    for (var item in ViewStyle) {
        this.bigDiv.style[item] = ViewStyle[item];
    }
}
Magnifier.prototype.MainEvent = function () {
    var _this = this;
    this.mask.onmouseover = function () {
        _this.bigDiv.style.display = "block";
        _this.mirror.style.display = "block";
    }
    this.mask.onmouseout = function () {
        _this.bigDiv.style.display = "none";
        _this.mirror.style.display = "none";
    }
    this.mask.onmousemove = function (evt) {
        var oEvent = evt || event;
        // 相容 Firefox
        var disX = oEvent.offsetX || oEvent.layerX;
        var disY = oEvent.offsetY || oEvent.layerY;
        var mirrorLeft = disX - _this.mirror.offsetWidth / 2;
        var mirrorTop = disY - _this.mirror.offsetHeight / 2;
        if (mirrorLeft < 0) {
            mirrorLeft = 0;
        }
        else if (mirrorLeft > this.offsetWidth - _this.mirror.offsetWidth) {
            mirrorLeft = this.offsetWidth - _this.mirror.offsetWidth;
        }
        if (mirrorTop < 0) {
            mirrorTop = 0;
        }
        else if (mirrorTop > this.offsetHeight - _this.mirror.offsetHeight) {
            mirrorTop = this.offsetHeight - _this.mirror.offsetHeight;
        }
        _this.mirror.style.top = mirrorTop + "px";
        _this.mirror.style.left = mirrorLeft + "px";
        var paX = mirrorTop / (this.offsetHeight - _this.mirror.offsetHeight);
        var paY = mirrorLeft / (this.offsetWidth - _this.mirror.offsetWidth);
        _this.bigImg.style.top = -paX * (_this.bigImg.offsetHeight - _this.bigDiv.offsetHeight) + "px";
        _this.bigImg.style.left = -paY * (_this.bigImg.offsetWidth - _this.bigDiv.offsetWidth) + "px";
    }
}
Magnifier.prototype.$ = function (id) {
    return document.getElementById(id);
}
Magnifier.prototype.$Create = function (type) {
    return document.createElement(type);
}

封裝完成後,在 onload 時只需一行 new 就能輕鬆調用,並自由傳入鏡片與預覽窗的樣式:

window.onload = function () {
    new Magnifier(
        "Magnifier",
        "images/Magnifier/small.jpg",
        "images/Magnifier/big.jpg",
        { "width": "30px", "height": "30px", "backgroundColor": "#fff" },
        { "width": "250px", "height": "250px" }
    );
}

以上就是本文的全部內容。從跑通核心算法到封裝成可重複使用的類別,希望這個放大鏡的實作過程能給你一些啟發,也祝大家都能寫出自己順手的小工具。

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