本段整理四個實務面的差異:location.href 的版本差異、模態視窗、frame 操作,以及 body 對象的可用時機。
IE 或 Firefox 2.0.x 下,可以使用 window.location 或 window.location.href;Firefox 1.5.x 下只能使用 window.location。解法是統一改用 window.location 取代 window.location.href。
IE 可以透過 showModalDialog 與 showModelessDialog 打開模態與非模態視窗,Firefox 不支援。解法是直接用 window.open(pageURL, name, parameters) 打開新視窗。
若需要把子視窗中的參數傳回父視窗,可在子視窗中用 window.opener 存取父視窗:
var parWin = window.opener;
parWin.document.getElementById("Aqing").value = "Aqing";
以下面這個 frame 為例:
<frame src="xxx.html" id="frameId" name="frameName" />
存取 frame 對象:IE 可用 window.frameId 或 window.frameName;Firefox 只能用 window.frameName。此外,兩者都支援 window.document.getElementById("frameId")。
切換 frame 內容:兩者都可使用 window.document.getElementById("testFrame").src = "xxx.html" 或 window.frameName.location = "xxx.html"。
若要把 frame 中的參數傳回父視窗,可在 frame 中使用 parent 存取父視窗,例如 parent.document.form1.filename.value = "Aqing";。
Firefox 的 body 在 body 標籤尚未被完全讀入之前就存在;IE 的 body 則必須在 body 標籤被完全讀入之後才存在。因此同樣一段掛在 body 上的事件綁定,位置不同就會有兩種結果。
Firefox 可以這樣寫:
<body>
<script type="text/JavaScript">
document.body.onclick = function(evt){
evt = evt || window.event;
alert(evt);
}
</script>
</body>
若要同時相容 IE 與 Firefox,把 script 移到 body 結束標籤之後:
<body></body>
<script type="text/JavaScript">
document.body.onclick = function(evt){
evt = evt || window.event;
alert(evt);
}
</script>