標籤:style blog http java color 使用
我不想挑起IE與Firefox之間的爭論,我只想說說Firefox瀏覽器有而IE裡沒有的一個功能,對DOM裡的對象原型的擴充。 在DOM裡的window、document、element、event等這些對象在Firefox(或者說Mozilla核心的瀏覽器)裡都有與之對應的原型:Window、HTMLDocument、HTMLElement、Event等,對於這些原型擴充之後,那些window、document等對象就“自動”擁有某些成員屬性或者成員方法了。舉個簡單的例子,比如在IE裡都有一個 outerHTML 屬性,可以取得這些元素所有的細節資訊,但是這個屬性不是W3C標準屬性,所以那些非IE的瀏覽器就不會擁有這種屬性了。不過因為這個屬性使用起來非常方便,我想在Firefox之類的瀏覽器裡也使用這個屬性那該怎麼辦呢?這裡就要用到原型擴充了:<script type="text/javascript">/*<![CDATA[*/if(typeof(HTMLElement)!="undefined" && !window.opera){ HTMLElement.prototype.__defineGetter__("outerHTML",function() { var a=this.attributes, str="<"+this.tagName, i=0;for(;i<a.length;i++) if(a[i].specified) str+=" "+a[i].name+‘="‘+a[i].value+‘"‘; if(!this.canHaveChildren) return str+" />"; return str+">"+this.innerHTML+"</"+this.tagName+">"; }); HTMLElement.prototype.__defineSetter__("outerHTML",function(s) { var r = this.ownerDocument.createRange(); r.setStartBefore(this); var df = r.createContextualFragment(s); this.parentNode.replaceChild(df, this); return s; }); HTMLElement.prototype.__defineGetter__("canHaveChildren",function() { return !/^(area|base|basefont|col|frame|hr|img|br|input|isindex|link|meta|param)$/.test(this.tagName.toLowerCase()); });}/*]]>*/</script> 加了這麼一段代碼之後,在Firefox瀏覽器裡再調用 document.getElementById("divId").outerHTML,(讀取/賦值)一切正常,這一點優勢是IE系列瀏覽器所不具有的。這一點算是 Firefox 瀏覽器(Mozilla核心的瀏覽器)的一個亮點吧! 下面再寫兩個比較有用的擴充吧:<script type="text/javascript">/*<![CDATA[*/if(!window.attachEvent && window.addEventListener){ Window.prototype.attachEvent = HTMLDocument.prototype.attachEvent= HTMLElement.prototype.attachEvent=function(en, func, cancelBubble) { var cb = cancelBubble ? true : false; this.addEventListener(en.toLowerCase().substr(2), func, cb); }; Window.prototype.detachEvent = HTMLDocument.prototype.detachEvent= HTMLElement.prototype.detachEvent=function(en, func, cancelBubble) { var cb = cancelBubble ? true : false; this.removeEventListener(en.toLowerCase().substr(2), func, cb); };}if(typeof Event!="undefined" && !window.opera){ var t=Event.prototype; t.__defineSetter__("returnValue", function(b){if(!b)this.preventDefault(); return b;}); t.__defineSetter__("cancelBubble",function(b){if(b) this.stopPropagation(); return b;}); t.__defineGetter__("offsetX", function(){return this.layerX;}); t.__defineGetter__("offsetY", function(){return this.layerY;}); t.__defineGetter__("srcElement", function(){var n=this.target; while (n.nodeType!=1)n=n.parentNode;return n;}); }/*]]>*/</script>以上的代碼都是截取於我寫的 jsframewrok 架構。 View Code