DIV CSS 佈局教程網

用JavaScript實作5秒後自動關閉div廣告層的教學
編輯:關於JavaScript     

本文示範如何製作一個頁面載入後顯示於中央、並在倒數 5 秒後自動關閉的 div 浮層,常見於首頁彈出廣告或公告。完整程式碼如下:

代碼如下:<html>
<head>
<title>JS實現5秒鐘自動封鎖div層</title>
<style type="text/css">
<!--
#sponsorAdDiv {position:absolute; height:1; width:1; top:0; left:0;}
-->
</style>
</head>
<body>
<SCRIPT LANGUAGE="JavaScript1.2">
adTime=5;   //封鎖窗口期待的時間
chanceAd=1;
var ns=(document.layers);
var ie=(document.all);
var w3=(document.getElementById && !ie);
adCount=0;
function initAd(){
        if(!ns && !ie && !w3) return;
        if(ie)                 adDiv=eval('document.all.sponsorAdDiv.style');
        else if(ns)         adDiv=eval('document.layers["sponsorAdDiv"]');
        else if(w3)         adDiv=eval('document.getElementById("sponsorAdDiv").style');
        randAd=Math.ceil(Math.random()*chanceAd);
        if (ie||w3)
        adDiv.visibility="visible";
        else
        adDiv.visibility ="show";
        if(randAd==1) showAd();
}
function showAd(){
if(adCount<adTime*10){adCount+=1;
        if (ie){documentWidth  =document.body.offsetWidth/2+document.body.scrollLeft-20;
        documentHeight =document.body.offsetHeight/2+document.body.scrollTop-20;}
        else if (ns){documentWidth=window.innerWidth/2+window.pageXOffset-20;
        documentHeight=window.innerHeight/2+window.pageYOffset-20;}
        else if (w3){documentWidth=self.innerWidth/2+window.pageXOffset-20;
        documentHeight=self.innerHeight/2+window.pageYOffset-20;}
        adDiv.left=documentWidth-200;adDiv.top =documentHeight-200;
        setTimeout("showAd()",100);}else closeAd();
}
function closeAd(){
if (ie||w3)
adDiv.display="none";
else
adDiv.visibility ="hide";
}
onload=initAd;
</script>
<div id="sponsorAdDiv" style="visibility:hidden">
<table width="450" height="350" bgcolor="008000"><tr><td>
<table width="445" height="345" bgcolor="F0FFF0"><tr><td>
<center>welcome to www.CsrCode.cn!<BR><BR>這個窗口將在5秒後自動封鎖</center>
</td></tr></table></td></tr></table></div>
</body>
</html>

原理是利用 setTimeout 每 100 毫秒遞迴呼叫 showAd 並累加計數 adCount,當計數達到 adTime×10(即 5 秒)時呼叫 closeAd 隱藏浮層;同時依視窗寬高把浮層置中。程式並對 IE、Netscape 與標準瀏覽器做了相容判斷。希望本文對你的 JavaScript 開發有所幫助。

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