贴一个在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 相关文章推荐
Prototype源码浅析 Enumerable部分(二)
Jan 18 Javascript
js随机颜色代码的多种实现方式
Apr 23 Javascript
JavaScript中setAttribute用法介绍
Jul 20 Javascript
在JavaScript中重写jQuery对象的方法实例教程
Aug 25 Javascript
javascript检测浏览器的缩放状态实现代码
Sep 28 Javascript
JS数组(Array)处理函数整理
Dec 07 Javascript
JavaScript返回0-1之间随机数的方法
Apr 06 Javascript
js验证真实姓名与身份证号是否匹配
Oct 13 Javascript
jquery实现ajax加载超时提示的方法
Jul 23 Javascript
微信小程序 支付功能开发错误总结
Feb 21 Javascript
Vue 2.0+Vue-router构建一个简单的单页应用(附源码)
Mar 14 Javascript
在vue.js中抽出公共代码的方法示例
Jun 08 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 获取全局变量的代码
2011/04/21 PHP
PHP中通过fopen()函数访问远程文件示例
2014/11/18 PHP
php 在线导入mysql大数据程序
2015/06/11 PHP
PHP中Enum(枚举)用法实例详解
2015/12/07 PHP
php获取用户真实IP和防刷机制的实例代码
2018/11/28 PHP
指定js可访问其它域名的cookie的方法
2007/09/18 Javascript
JavaScript在IE和Firefox浏览器下的7个差异兼容写法小结
2010/06/18 Javascript
Jquery Ajax解析XML数据(同步及异步调用)简单实例
2014/02/12 Javascript
JavaScript中使用stopPropagation函数停止事件传播例子
2014/08/27 Javascript
jQuery中checkbox反复调用attr('checked', true/false)只有第一次生效的解决方法
2016/11/16 Javascript
jquery插件开发模式实例详解
2019/07/20 jQuery
nodejs中使用worker_threads来创建新的线程的方法
2021/01/22 NodeJs
Python中给List添加元素的4种方法分享
2014/11/28 Python
Python中的匿名函数使用简介
2015/04/27 Python
python实现用户登陆邮件通知的方法
2015/07/09 Python
python3.4下django集成使用xadmin后台的方法
2017/08/15 Python
浅谈numpy生成数组的零值问题
2018/11/12 Python
Python神奇的内置函数locals的实例讲解
2019/02/22 Python
深度辨析Python的eval()与exec()的方法
2019/03/26 Python
如何在Cloud Studio上执行Python代码?
2019/08/09 Python
FFrpc python客户端lib使用解析
2019/08/24 Python
Python hmac模块使用实例解析
2019/12/24 Python
tensorflow没有output结点,存储成pb文件的例子
2020/01/04 Python
新手入门学习python Numpy基础操作
2020/03/02 Python
python转化excel数字日期为标准日期操作
2020/07/14 Python
HTML5 中新的全局属性(整理)
2013/07/31 HTML / CSS
HTML5新特性之type=file文件上传功能
2018/02/02 HTML / CSS
地理科学专业毕业生求职信
2013/10/15 职场文书
军训生自我鉴定范文
2013/12/27 职场文书
九月份红领巾广播稿
2014/01/22 职场文书
中学教师暑期培训方案
2014/08/27 职场文书
员工培训协议书
2014/09/15 职场文书
学术研讨会欢迎词
2015/01/26 职场文书
Win10鼠标轨迹怎么开 Win10显示鼠标轨迹方法
2022/04/06 数码科技
引用计数法和root搜索算法以及JVM中判定对象需要回收的方法
2022/04/19 Java/Android
JAVA 线程池(池化技术)的实现原理
2022/04/28 Java/Android