DIV CSS 佈局教程網

打造可自訂 HTML 內容的類彈出視窗
編輯:JQuery特效代碼     

有時不想引入龐大的彈窗外掛,只想做一個簡單、可自由放入 HTML 內容的彈出視窗。透過 jQuery 搭配一層半透明遮罩,就能自己實作一個偽彈出框。

JavaScript 部分:

var popupStatus = 0;
//載入彈出框
function loadPopup(){
if(popupStatus==0){
$("#backgroundPopup").css({ "opacity": "0.7" });
$("#backgroundPopup").fadeIn("slow");
$("#popupContact").fadeIn("slow");
popupStatus = 1;
}
}
//關閉彈出框
function disablePopup(){
if(popupStatus==1){
$("#backgroundPopup").fadeOut("slow");
$("#popupContact").fadeOut("slow");
popupStatus = 0;
}
}
//置中彈出框
function centerPopup(){
var browser=navigator.userAgent;
var windowWidth = document.documentElement.clientWidth;
var windowHeight = document.documentElement.clientHeight;
var stop="", sleft="";
if(browser.indexOf('Chrome')!=-1){
stop=document.body.scrollTop; sleft=document.body.scrollLeft;
} else {
stop=document.documentElement.scrollTop; sleft=document.documentElement.scrollLeft;
}
var popupHeight = $("#popupContact").height();
var popupWidth = $("#popupContact").width();
$("#popupContact").css({
"position": "absolute",
"top": windowHeight/2-popupHeight/2+stop,
"left": windowWidth/2-popupWidth/2+sleft
});
$("#backgroundPopup").css({ "height": windowHeight });
}
//呼叫彈出框
function bb(str){
$("#download").show();
centerPopup();
loadPopup();
$("#popupContactClose").click(function(){ disablePopup(); });
$("#backgroundPopup").click(function(){ disablePopup(); });
$(document).keypress(function(e){
if(e.keyCode==27 && popupStatus==1){ disablePopup(); }
});
}

HTML 部分(預設隱藏):

<div id="download" style="display: none;">
<div id="popupContact">
<!--在這裡放入自己的 HTML 內容-->
</div>
<div id="backgroundPopup"></div>
</div>

整個實作的關鍵在於:用一個 popupStatus 變數記錄彈窗目前的開關狀態,避免重複觸發;centerPopup 依視窗與捲動位置把彈窗置中;而關閉則支援三種方式——點右上角、點背景遮罩、或按 Esc 鍵(keyCode 27)。置中計算時特別針對 Chrome 與其他瀏覽器取得 scrollTop/Left 的方式差異做了處理。

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