DIV CSS 佈局教程網

手把手做一個簡單的 jQuery 插件 dBox
編輯:JQuery特效代碼     

一、先包一個閉包

(function ($) {
  // code in here
})(jQuery);

這是 jQuery 官方的外掛開發規範,好處有三:避免全域依賴、避免被第三方覆蓋、同時相容 $ 與 jQuery 兩個操作符。

二、加入骨架

$.fn.dBox = function (options) {
  var defaults = {
    // 各種屬性及其預設值
  };
  var opts = $.extend(defaults, options);
  // function codes in here
};

dBox 是我替這個彈出層外掛取的名字。

三、定義屬性與預設值

$.fn.dBox = function (options) {
  var defaults = {
    opacity: 0.6,      // 遮罩層透明度
    drag: true,        // 是否可拖曳
    title: 'dBox',
    content: '',
    left: 400,
    top: 200,
    width: 600,
    height: 300,
    setPos: false,     // 是否使用自訂的 left / top
    overlay: true,     // 是否顯示遮罩層
    loadStr: 'Loading',
    ajaxSrc: '',
    iframeSrc: ''
  };
  var opts = $.extend(defaults, options);
  // function codes in here
};

四、把彈出層與遮罩層的 HTML 組出來

為了示範方便,這裡把樣式直接內嵌在 style 屬性中:

// build html code of the dBox
var dBoxHtml = "<div id='dBox' style='background-color:#FFF;border:solid 2px #00E;position:absolute;z-index:100;'>";
dBoxHtml += "<div id='d_head' style='width:100%;height:20px;border-bottom:solid 1px #00E;'>";
dBoxHtml += "<div id='d_title' style='float:left;width:90%;color:#00E'>" + opts.title + "</div>";
dBoxHtml += "<div id='d_close' style='float:right;cursor:pointer;margin-right:5px;color:#00E'>[x]</div>";
dBoxHtml += "</div>";
dBoxHtml += "<div id='d_content' style='width:100%;height:100%;padding:3px;'>" + opts.content + "</div>";
dBoxHtml += "</div>";

var dBoxBG = "<iframe id='d_iframebg' style='position:absolute;top:0;left:0;width:0;height:0;border:none;'></iframe>"
           + "<div id='d_bg' style='background-color:#000;z-index:99;position:absolute;top:0;left:0;'></div>";

var loading = "<div id='d_loading' style='position:fixed;top:48%;left:48%;z-index:100;border:solid 1px #000;'>"
            + opts.loadStr + "</div>";

為什麼遮罩層要多一個 iframe?因為 IE6 的 z-index 對 select 下拉清單無效,下拉會浮在遮罩上層。放一個 iframe 墊在遮罩後面就能壓住它——這是那個年代處理 IE6 的標準手法。

五、綁定點擊事件

// click event
$(this).click(function () {
  $("body").append(dBoxHtml);

  // case ajax
  if (opts.ajaxSrc != "") {
    $("#d_content").append("<div id='d_ajax' style='width:" + (opts.width - 6)
      + "px;height:" + (opts.height - 26) + "px;overflow:scroll;'><div id='d_ajaxcontent'></div></div>");
    $("#d_ajaxcontent").load(opts.ajaxSrc);
  }
  // case iframe
  else if (opts.iframeSrc != "") {
    $("#d_content").append("<iframe frameborder='0' width='" + (opts.width - 6)
      + "' height='" + (opts.height - 26) + "' src='" + opts.iframeSrc + "'>");
  }

  addCSS();
  if (opts.drag == true) { drag(); }
  $("#d_close").click(dBoxRemove);
  return false;
});

最後的 return false 會取消瀏覽器預設行為,所以就算把這段綁在 <a> 上也不會跳轉。事件流程是:先注入框架 → 依 ajaxSrc / iframeSrc 決定內容載入方式 → 套用樣式與定位 → 視需要啟用拖曳 → 綁定關閉。

六、三個輔助事件

addCSS():定位與遮罩

function addCSS() {
  var pos = setPosition();
  $("#dBox").css({ "left": pos[0], "top": pos[1],
                   "width": opts.width + "px", "height": opts.height + "px" });
  if (opts.overlay) {
    var wh = getPageSize();
    $(dBoxBG).appendTo("body").css({ "opacity": opts.opacity,
                                     "width": wh[0], "height": wh[1] });
  }
}

// 取頁面尺寸,讓遮罩能蓋滿整份文件
function getPageSize() {
  if ($(window).height() > $(document).height()) { h = $(window).height(); }
  else { h = $(document).height(); }
  w = $(window).width();
  return Array(w, h);
}

// 計算置中位置
function setPosition() {
  if (opts.setPos) { l = opts.left; t = opts.top; }
  else {
    var w = opts.width, h = opts.height;
    var width = $(document).width(), height = $(window).height();
    var left = $(document).scrollLeft(), top = $(document).scrollTop();
    t = top + (height / 2) - (h / 2);
    l = left + (width / 2) - (w / 2);
  }
  return Array(l, t);
}

置中計算加上 scrollTop / scrollLeft 是必要的,否則頁面捲動後彈出層會跑到錯誤的位置。

drag():拖曳

function drag() {
  var dx, dy, moveout;
  var handle = $("#dBox").find("#d_head>#d_title").css('cursor', 'move');

  handle.mousedown(function (e) {
    dx = e.clientX - parseInt($("#dBox").css("left"));
    dy = e.clientY - parseInt($("#dBox").css("top"));
    $("#dBox").mousemove(move).mouseout(out).css({ "opacity": opts.opacity });
    handle.mouseup(up);
  });

  move = function (e) {
    moveout = false;
    win = $(window);
    var x, y;
    if (e.clientX - dx < 0) { x = 0; }
    else if (e.clientX - dx > (win.width() - $("#dBox").width())) {
      x = win.width() - $("#dBox").width();     // 右邊界
    } else { x = e.clientX - dx; }

    if (e.clientY - dy < 0) { y = 0; } else { y = e.clientY - dy; }
    $("#dBox").css({ left: x, top: y });
  };

  out = function (e) {
    moveout = true;
    setTimeout(function () { moveout && up(e); }, 10);
  };

  up = function (e) {
    $("#dBox").unbind("mousemove", move).unbind("mouseout", out).css("opacity", 1);
    handle.unbind("mouseup", up);
  };
}

dx / dy 記錄滑鼠按下瞬間與彈出層左上角之間的偏移量,拖曳時用這個偏移去反推新座標,這樣元素才不會在按下的那一刻突然跳到滑鼠中心。左右與上邊做了邊界夾制,避免拖出視窗外。

dBoxRemove():關閉

function dBoxRemove() {
  if ($("#dBox")) {
    $("#dBox").stop().fadeOut(200, function () {
      $("#dBox").remove();
      if (opts.overlay) {
        $("#d_bg").remove();
        $("#d_iframebg").remove();
      }
    });
  }
}

淡出動畫結束後才 remove,遮罩與 iframe 墊片也要一起清掉,否則會留下一層看不見卻擋滑鼠的黑色遮罩——這個 bug 在實際使用時相當惱人。

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