十、層
1. 層內放置外部檔案(External Files Within Layers)
Q:我可以在將外部的HTML檔案作為頁面的一部分顯示嗎。
A:可以,你可以通過使用下面方法實現: LAYER或者ILAYER標記,SRC=FILENAME.HTM(在Netscape4中) IFRAME標記,SRC=FILENAME.HTM(在Explore4+ 和 Netscape 6中)
你可以使用JavaScript檢測瀏覽器的名稱和版本(見用戶端資訊),然後產生需要的IFRAME或者LAYER標記。
這是一個例子:
在上面的例子中,我們建立了一個JavaScript函數insertExternalFile(),用來檢測用戶端瀏覽器和產生必要的標記。為了插入外部檔案,我們調用insertExternalFile()時,將檔案名稱作為一個參數。這個函數還有另外兩個參數:用來顯示插入檔案地區的寬和高。因此,外部檔案inserted_file1.htm和inserted_file2.htm就通過下面的代碼被嵌入到頁面中:
insertExternalFile("inserted_file.htm",layer_width,layer_height)
下面的JavaScript代碼是包含在頁面HEAD地區的insertExternalFile():
<script language="JavaScript"><!--function insertExternalFile(fname,W,H) { if (navigator.appName.indexOf("Microsoft")!=-1 || navigator.appName=="Netscape" && parseInt(navigator.appVersion)>4 ) { document.write('' +'<IFRAME src="'+fname+'" scrolling="no" frameborder=0 border=0' +(W==null ? '' : ' width='+W) +(H==null ? '' : ' height='+H) +'></IFRAME>' ) } if (navigator.appName=="Netscape" && parseInt(navigator.appVersion)==4) { document.write('' +'<ILAYER>' +'<LAYER src="'+fname+'" ' +(W==null ? '' : ' width='+W) +(H==null ? '' : ' height='+H) +'></LAYER></ILAYER>' ) }}//--></script>
2. 建立層(Creating Layers)
Q:我如何通過JavaScript建立一個新層。
A:正常情況下,你可以通過在頁面的HTML代碼中使用DIV建立層。不過,你也可以通過JavaScript建立。下面是一個例子:
上面的例子使用了代碼:
<form><input type=button value="Create layer"onClick="makeLayer('LYR1',200,10,100,100,'red',1,1)"><input type=button value="Delete layer"onClick="deleteLayer('LYR1')"></form>
這段代碼調用 makeLayer來建立一個新層:
makeLayer(ID,left,top,width,height,color,visible,zIndex)
這個函數的JavaScript源碼是:
function makeLayer(id,L,T,W,H,bgColor,visible,zIndex) { if (document.layers) { if (document.layers[id]) { alert ('Layer with this ID already exists!') return } var LR=document.layers[id]=new Layer(W) LR.name= id LR.left= L LR.top = T LR.clip.height=H LR.visibility=(null==visible || 1==visible ? 'show' : 'hide') if(null!=zIndex) LR.zIndex=zIndex if(null!=bgColor) LR.bgColor=bgColor } else if (document.all) { if (document.all[id]) { alert ('Layer with this ID already exists!') return } var LR= '/n<DIV id='+id+' style="position:absolute' +'; left:'+L +'; top:'+T +'; width:'+W +'; height:'+H +'; clip:rect(0,'+W+','+H+',0)' +'; visibility:'+(null==visible || 1==visible ? 'visible':'hidden') +(null==zIndex ? '' : '; z-index:'+zIndex) +(null==bgColor ? '' : '; background-color:'+bgColor) +'"></DIV>' document.body.insertAdjacentHTML("BeforeEnd",LR) }}
3. 刪除層(Deleting Layers)
Q:我可以通過JavaScript刪除一個層嗎。
A:這個例子在建立層部分已經看到過了:
這個例子由下面的代碼建立:
<form><input type=button value="Create layer"onClick="makeLayer('LYR1',200,10,100,100,'red',1,1)"><input type=button value="Delete layer"onClick="deleteLayer('LYR1')"></form>
要刪除一個層,就將層的ID作為參數調用deleteLayer(id)函數。下面是這個函數的源碼:
function deleteLayer(id) { if (document.layers && document.layers[id]) { document.layers[id].visibility='hide' delete document.layers[id] } if (document.all && document.all[id]) { document.all[id].innerHTML='' document.all[id].outerHTML='' }}