贴一个在Mozilla中常用的Javascript代码


Posted in Javascript onJanuary 09, 2007

Mozilla中独有的读写器(defineGetter、defineSetter)以及可以给Element,Event等加上prototype原型,使得在IE里用的方法同样在Mozilla中可以适用,下面贴出常用的一些代码
例如
obj.insertAdjacentHTML, currentStyle, obj.attachEvent, obj.detachEvent等等。

版权属于Erik Arvidsson, webfx

if (Browser.isMozilla) { // set up ie environment for Moz      
  extendEventObject();  
  emulateAttachEvent();  
  emulateEventHandlers(["click", "dblclick", "mouseover", "mouseout",  
              "mousedown", "mouseup", "mousemove",  
              "keydown", "keypress", "keyup"]);  
  emulateCurrentStyle();  
  /*emulateDocumentAll();  
  emulateElement()  
  */  
  // It is better to use a constant for event.button  
  Event.LEFT = 0;  
  Event.MIDDLE = 1;  
  Event.RIGHT = 2;  
}  
else {  
  Event = {};  
  // IE is returning wrong button number  
  Event.LEFT = 1;  
  Event.MIDDLE = 4;  
  Event.RIGHT = 2;  
}  
/*  
 * Extends the event object with srcElement, cancelBubble, returnValue,  
 * fromElement and toElement  
 */  
function extendEventObject() {  
  Event.prototype.__defineSetter__("returnValue", function (b) {  
    if (!b) this.preventDefault();  
    return b;  
  });  
  Event.prototype.__defineSetter__("cancelBubble", function (b) {  
    if (b) this.stopPropagation();  
    return b;  
  });  
  Event.prototype.__defineGetter__("srcElement", function () {  
    var node = this.target;  
    while (node.nodeType != 1) node = node.parentNode;  
    return node;  
  });  
  Event.prototype.__defineGetter__("fromElement", function () {  
    var node;  
    if (this.type == "mouseover")  
      node = this.relatedTarget;  
    else if (this.type == "mouseout")  
      node = this.target;  
    if (!node) return;  
    while (node.nodeType != 1) node = node.parentNode;  
    return node;  
  });  
  Event.prototype.__defineGetter__("toElement", function () {  
    var node;  
    if (this.type == "mouseout")  
      node = this.relatedTarget;  
    else if (this.type == "mouseover")  
      node = this.target;  
    if (!node) return;  
    while (node.nodeType != 1) node = node.parentNode;  
    return node;  
  });  
  Event.prototype.__defineGetter__("offsetX", function () {  
    return this.layerX;  
  });  
  Event.prototype.__defineGetter__("offsetY", function () {  
    return this.layerY;  
  });  
}  
/*  
 * Emulates element.attachEvent as well as detachEvent  
 */  
function emulateAttachEvent() {  
  HTMLDocument.prototype.attachEvent =  
  HTMLElement.prototype.attachEvent = function (sType, fHandler) {  
    var shortTypeName = sType.replace(/on/, "");  
    fHandler._ieEmuEventHandler = function (e) {  
      window.event = e;  
      return fHandler();  
    };  
    this.addEventListener(shortTypeName, fHandler._ieEmuEventHandler, false);  
  };  
  HTMLDocument.prototype.detachEvent =  
  HTMLElement.prototype.detachEvent = function (sType, fHandler) {  
    var shortTypeName = sType.replace(/on/, "");  
    if (typeof fHandler._ieEmuEventHandler == "function")  
      this.removeEventListener(shortTypeName, fHandler._ieEmuEventHandler, false);  
    else  
      this.removeEventListener(shortTypeName, fHandler, true);  
  };  
}  
/*  
 * This function binds the event object passed along in an  
 * event to window.event  
 */  
function emulateEventHandlers(eventNames) {  
  for (var i = 0; i < eventNames.length; i++) {  
    document.addEventListener(eventNames[i], function (e) {  
      window.event = e;  
    }, true);  // using capture  
  }  
}  
/*  
 * Simple emulation of document.all  
 * this one is far from complete. Be cautious  
 */  
function emulateAllModel() {  
  var allGetter = function () {  
    var a = this.getElementsByTagName("*");  
    var node = this;  
    a.tags = function (sTagName) {  
      return node.getElementsByTagName(sTagName);  
    };  
    return a;  
  };  
  HTMLDocument.prototype.__defineGetter__("all", allGetter);  
  HTMLElement.prototype.__defineGetter__("all", allGetter);  
}  
function extendElementModel() {  
  HTMLElement.prototype.__defineGetter__("parentElement", function () {  
    if (this.parentNode == this.ownerDocument) return null;  
    return this.parentNode;  
  });  
  HTMLElement.prototype.__defineGetter__("children", function () {  
    var tmp = [];  
    var j = 0;  
    var n;  
    for (var i = 0; i < this.childNodes.length; i++) {  
      n = this.childNodes[i];  
      if (n.nodeType == 1) {  
        tmp[j++] = n;  
        if (n.name) {  // named children  
          if (!tmp[n.name])  
            tmp[n.name] = [];  
          tmp[n.name][tmp[n.name].length] = n;  
        }  
        if (n.id)    // child with id  
          tmp[n.id] = n  
      }  
    }  
    return tmp;  
  });  
  HTMLElement.prototype.contains = function (oEl) {  
    if (oEl == this) return true;  
    if (oEl == null) return false;  
    return this.contains(oEl.parentNode);  
  };  
}  
function emulateCurrentStyle() {  
  HTMLElement.prototype.__defineGetter__("currentStyle", function () {  
    return this.ownerDocument.defaultView.getComputedStyle(this, null);  
    /*  
    var cs = {};  
    var el = this;  
    for (var i = 0; i < properties.length; i++) {  
      cs.__defineGetter__(properties[i], encapsulateObjects(el, properties[i]));  
    }  
    return cs;  
    */  
  });  
}  
function emulateHTMLModel() {  
  // This function is used to generate a html string for the text properties/methods  
  // It replaces '\n' with "<BR"> as well as fixes consecutive white spaces  
  // It also repalaces some special characters  
  function convertTextToHTML(s) {  
    s = s.replace(/\&/g, "&").replace(/</g, "<").replace(/>/g, ">").replace(/\n/g, "<BR>");  
    while (/\s\s/.test(s))  
      s = s.replace(/\s\s/, "  ");  
    return s.replace(/\s/g, " ");  
  }  
  HTMLElement.prototype.insertAdjacentHTML = function (sWhere, sHTML) {  
    var df;  // : DocumentFragment  
    var r = this.ownerDocument.createRange();  
    switch (String(sWhere).toLowerCase()) {  
      case "beforebegin":  
        r.setStartBefore(this);  
        df = r.createContextualFragment(sHTML);  
        this.parentNode.insertBefore(df, this);  
        break;  
      case "afterbegin":  
        r.selectNodeContents(this);  
        r.collapse(true);  
        df = r.createContextualFragment(sHTML);  
        this.insertBefore(df, this.firstChild);  
        break;  
      case "beforeend":  
        r.selectNodeContents(this);  
        r.collapse(false);  
        df = r.createContextualFragment(sHTML);  
        this.appendChild(df);  
        break;  
      case "afterend":  
        r.setStartAfter(this);  
        df = r.createContextualFragment(sHTML);  
        this.parentNode.insertBefore(df, this.nextSibling);  
        break;  
    }  
  };  
  HTMLElement.prototype.__defineSetter__("outerHTML", function (sHTML) {  
   var r = this.ownerDocument.createRange();  
   r.setStartBefore(this);  
   var df = r.createContextualFragment(sHTML);  
   this.parentNode.replaceChild(df, this);  
   return sHTML;  
  });  
  HTMLElement.prototype.__defineGetter__("canHaveChildren", function () {  
    switch (this.tagName) {  
      case "AREA":  
      case "BASE":  
      case "BASEFONT":  
      case "COL":  
      case "FRAME":  
      case "HR":  
      case "IMG":  
      case "BR":  
      case "INPUT":  
      case "ISINDEX":  
      case "LINK":  
      case "META":  
      case "PARAM":  
        return false;  
    }  
    return true;  
  });  
  HTMLElement.prototype.__defineGetter__("outerHTML", function () {  
    var attr, attrs = this.attributes;  
    var str = "<" + this.tagName;  
    for (var i = 0; i < attrs.length; i++) {  
      attr = attrs[i];  
      if (attr.specified)  
        str += " " + attr.name + '="' + attr.value + '"';  
    }  
    if (!this.canHaveChildren)  
      return str + ">";  
    return str + ">" + this.innerHTML + "</" + this.tagName + ">";  
  });  
  HTMLElement.prototype.__defineSetter__("innerText", function (sText) {  
    this.innerHTML = convertTextToHTML(sText);  
    return sText;  
  });  
  var tmpGet;  
  HTMLElement.prototype.__defineGetter__("innerText", tmpGet = function () {  
    var r = this.ownerDocument.createRange();  
    r.selectNodeContents(this);  
    return r.toString();  
  });  
  HTMLElement.prototype.__defineSetter__("outerText", function (sText) {  
    this.outerHTML = convertTextToHTML(sText);  
    return sText;  
  });  
  HTMLElement.prototype.__defineGetter__("outerText", tmpGet);  
  HTMLElement.prototype.insertAdjacentText = function (sWhere, sText) {  
    this.insertAdjacentHTML(sWhere, convertTextToHTML(sText));  
  };  
}
Javascript 相关文章推荐
用javascript getComputedStyle获取和设置style的原理
Oct 10 Javascript
jQuery EasyUI API 中文文档 - DataGrid数据表格
Nov 17 Javascript
javascript中的onkeyup和onkeydown区别介绍
Apr 28 Javascript
页面图片浮动左右滑动效果的简单实现案例
Feb 10 Javascript
jquery简单实现带渐显效果的选项卡菜单代码
Sep 01 Javascript
jquery实现可旋转可拖拽的文字效果代码
Jan 27 Javascript
Bootstrap对话框使用实例讲解
Sep 24 Javascript
JS实现物体带缓冲的间歇运动效果示例
Dec 22 Javascript
Vue.js中轻松解决v-for执行出错的三个方案
Jun 09 Javascript
vue单页应用加百度统计代码(亲测有效)
Jan 31 Javascript
Vue组件内部实现一个双向数据绑定的实例代码
Apr 04 Javascript
javascript实现的字符串转换成数组操作示例
Jun 13 Javascript
Javascript-Mozilla和IE中的一个函数直接量的问题
Jan 09 #Javascript
Javascript调试工具(下载)
Jan 09 #Javascript
如何在Mozilla Gecko 用Javascript加载XSL
Jan 09 #Javascript
如何让动态插入的javascript脚本代码跑起来。
Jan 09 #Javascript
JS效率个人经验谈(8-15更新),加入range技巧
Jan 09 #Javascript
你所要知道JS(DHTML)中的一些技巧
Jan 09 #Javascript
sina的lightbox效果。
Jan 09 #Javascript
You might like
PHP 编程请选择正确的文本编辑软件
2006/12/21 PHP
解决中英文字符串长度问题函数
2007/01/16 PHP
php数组去重的函数代码
2013/02/03 PHP
dedecms函数分享之获取某一栏目所有子栏目
2014/05/19 PHP
php判断手机浏览还是web浏览,并执行相应的动作简单实例
2016/07/28 PHP
PHP自定义函数实现assign()数组分配到模板及extract()变量分配到模板功能示例
2018/05/23 PHP
当鼠标移动到图片上时跟随鼠标显示放大的图片效果
2013/06/06 Javascript
JavaScript实现两个Table固定表头根据页面大小自行调整
2014/01/03 Javascript
setTimeout自动触发一个js的方法
2014/01/15 Javascript
jQuery$命名冲突怎么办如何解决
2014/01/16 Javascript
jquery跨域请求示例分享(jquery发送ajax请求)
2014/03/25 Javascript
Redis基本知识、安装、部署、配置笔记
2015/03/05 Javascript
Javascript中的apply()方法浅析
2015/03/15 Javascript
基于jquery实现一个滚动的分步注册向导-附源码
2015/08/26 Javascript
Vue.js 2.0 和 React、Augular等其他前端框架大比拼
2016/10/08 Javascript
微信小程序 自己制作小组件实例详解
2016/12/22 Javascript
JS实现图片放大缩小的方法
2017/02/15 Javascript
jQuery+ajax实现局部刷新的两种方法
2017/06/08 jQuery
jquery实现左右轮播切换效果
2018/01/01 jQuery
微信小程序实现登录注册功能
2020/12/29 Javascript
在Python下使用Txt2Html实现网页过滤代理的教程
2015/04/11 Python
python基于socket实现网络广播的方法
2015/04/29 Python
python的变量与赋值详细分析
2017/11/08 Python
Python中关于浮点数的冷知识
2019/09/22 Python
python用quad、dblquad实现一维二维积分的实例详解
2019/11/20 Python
python实现TCP文件传输
2020/03/20 Python
anaconda升级sklearn版本的实现方法
2021/02/22 Python
Probikekit日本:自行车套件,跑步和铁人三项装备
2017/04/03 全球购物
健身场所或家用健身设备:Life Fitness
2017/11/01 全球购物
中国一家综合的外贸B2C电子商务网站:DealeXtreme(DX)
2020/03/10 全球购物
送货司机岗位职责
2013/12/11 职场文书
英文自荐信
2013/12/19 职场文书
大专生毕业的自我评价
2014/02/06 职场文书
《三亚落日》教学反思
2014/04/26 职场文书
工程部部长岗位职责
2015/02/12 职场文书
驳回起诉裁定书
2015/05/19 职场文书