首页 > 代码库 > Firefox 浏览器的DOM原型扩展

Firefox 浏览器的DOM原型扩展

  我不想挑起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