本段示範一個有趣的思路:用原型擴充的方式,在 Firefox 中補上 IE 特有的屬性介面,讓原本只為 IE 寫的程式碼得以運作。
if (window.addEventListener) {
FixPrototypeForGecko();
}
function FixPrototypeForGecko() {
HTMLElement.prototype.__defineGetter__("runtimeStyle", element_prototype_get_runtimeStyle);
window.constructor.prototype.__defineGetter__("event", window_prototype_get_event);
Event.prototype.__defineGetter__("srcElement", event_prototype_get_srcElement);
}
function element_prototype_get_runtimeStyle() {
return this.style; // 以 style 代替 runtimeStyle
}
function window_prototype_get_event() {
return SearchEvent();
}
function event_prototype_get_srcElement() {
return this.target;
}
function SearchEvent() {
if (document.all) return window.event; // IE
func = SearchEvent.caller;
while (func != null) {
var arg0 = func.arguments[0];
if (arg0) {
if (arg0.constructor == Event) return arg0;
}
func = func.caller;
}
return null;
}
由於 Firefox 與 IE 都支援 DOM 標準,使用 obj.parentNode 是比較好的選擇。IE 專用的 obj.parentElement 應該避免。
若要在前端用 document.getElementById 取得控制項,輸出 JavaScript 時必須改用控制項的 ClientID,而不是 UniqueID:
"JavaScript:OnSelectSubCatalog(\"" + subCatalog_drp.ClientID + "\"," + catalogIDX + "," + catID.ToString() + ")";
移除一個選項,IE 可以寫成:
sel.options.remove(sel.selectedIndex);
新增選項,IE 的寫法很直接:
subCatalog.add(new Option(text, value));
要在兩者相容,改用 DOM 標準的 createElement 做法:
var opnObj = document.createElement("OPTION");
opnObj.value = value;
opnObj.text = text;
subCatalog.appendChild(opnObj);
Firefox 不支援 cursor: hand,IE 則同時支援 hand 與 pointer,因此建議統一使用 pointer。