這個效果要實現的是:B 頁面裡有兩個層,一個是顯示層(暫稱為 c 層),一個是隱藏層(暫稱為 d 層)。單獨打開 B 頁面時,c 層顯示、d 層隱藏;而當你從 A 頁面連結過來時,則反過來讓 d 層顯示、c 層隱藏。我覺得這個技巧對網頁設計者會有不小的幫助,現在把代碼分享出來,這裡要感謝經典的「老二」提供的技術支援。
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "https://www.w3.org/TR/HTML4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=gb2312"> <title>這是 A 頁面</title> </head> <body> <a href="B.htm?id=show">我要連到 B 頁面</a> </body> </html>
關鍵在於連結網址帶上了參數 id=show,B 頁面正是靠它來判斷使用者是從哪裡進來的。
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=gb2312">
<title>這是 B 頁面</title>
<script language="Javascript">
function show()
{
var a=document.location.href;
//alert(a);
if(a.indexOf("id=show")==-1)
{
document.getElementById("hidden").style.display="none";
document.getElementById("show").style.display="block";
}
else
{
document.getElementById("hidden").style.display="block";
document.getElementById("show").style.display="none";
}
}
</script>
</head>
<body onload="show()">
<div id="hidden" style="display:none ">
<font color="red">這裡是一個隱藏的層,把我顯示出來吧,最好顯示我的時候把下面的那個層隱藏掉</font>
</div>
<div id="show">
<font color="blue">這是一個顯示的層</font>
</div>
</body>
</html>
原理其實很簡單:頁面載入時觸發 show() 函數,讀取當前網址;若網址中不含 id=show,就顯示 c 層、隱藏 d 層;若含有 id=show(也就是從 A 頁面點進來的),則反過來顯示 d 層、隱藏 c 層。透過這種方式,就能實現「依來源頁面決定顯示哪個層」的效果。