贴一个在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 相关文章推荐
JS 对象介绍
Jan 20 Javascript
基于jquery自己写tab滑动门(通用版)
Oct 30 Javascript
JavaScript动态创建link标签到head里的方法
Dec 22 Javascript
jQuery基本选择器(实例及表单域value的获取方法)
May 20 Javascript
使用jQuery调用XML实现无刷新即时聊天
Aug 07 Javascript
JS中实现函数return多个返回值的实例
Feb 21 Javascript
js轮播图透明度切换(带上下页和底部圆点切换)
Apr 27 Javascript
Angularjs上传文件组件flowjs功能
Aug 07 Javascript
vue引入ueditor及node后台配置详解
Jan 03 Javascript
详解基于DllPlugin和DllReferencePlugin的webpack构建优化
Jun 28 Javascript
微信小程序时间戳转日期的详解
Apr 30 Javascript
JS去除字符串最后的逗号实例分析【四种方法】
Jun 20 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生成局部唯一识别码LUID的代码
2012/10/06 PHP
php cURL和Rolling cURL并发方式比较
2013/10/30 PHP
PHP错误WARNING: SESSION_START() [FUNCTION.SESSION-START]解决方法
2014/05/04 PHP
php中header设置常见文件类型的content-type
2015/06/23 PHP
浅析php中array_map和array_walk的使用对比
2016/11/20 PHP
用Javascript读取中文COOKIE的解决办法
2007/02/15 Javascript
JavaScript页面刷新与弹出窗口问题的解决方法
2010/03/02 Javascript
Javascript 面向对象(二)封装代码
2012/05/23 Javascript
jQuery的Ajax的自动完成功能控件简要说明
2013/02/22 Javascript
jquery html动态添加的元素绑定事件详解
2016/05/24 Javascript
手机端图片缩放旋转全屏查看PhotoSwipe.js插件实现
2016/08/25 Javascript
angular中的http拦截器Interceptors的实现
2017/02/21 Javascript
JS基于正则表达式的替换操作(replace)用法示例
2017/04/28 Javascript
JavaScript实现简单评论功能
2017/08/17 Javascript
jQuery中event.target和this的区别详解
2020/08/13 jQuery
[50:28]LGD女子学院第三期 DOTA2复仇之魂教学
2013/12/24 DOTA
[01:12:35]Spirit vs Navi Supermajor小组赛 A组败者组第一轮 BO3 第二场 6.2
2018/06/03 DOTA
讲解Python中的标识运算符
2015/05/14 Python
基于MTCNN/TensorFlow实现人脸检测
2018/05/24 Python
Python实现Linux监控的方法
2019/05/16 Python
Django admin model 汉化显示文字的实现方法
2019/08/12 Python
Python数据正态性检验实现过程
2020/04/18 Python
jenkins+python自动化测试持续集成教程
2020/05/12 Python
python接入支付宝的实例操作
2020/07/20 Python
Python调用Redis的示例代码
2020/11/24 Python
CSS3 简写animation
2012/05/10 HTML / CSS
canvas离屏技术与放大镜实现代码示例
2018/08/31 HTML / CSS
Timberland澳大利亚官网:全球领先的户外品牌
2019/12/10 全球购物
Puccini乌克兰:购买行李箱、女士手袋网上商店
2020/08/06 全球购物
DBA数据库管理员JAVA程序员架构师必看
2016/02/07 面试题
护理学毕业生求职信
2013/11/14 职场文书
办公室前台岗位职责
2014/01/04 职场文书
2014年教研工作总结
2014/12/06 职场文书
婚宴主持词
2015/06/30 职场文书
如何拟写通知正文?
2019/04/02 职场文书
一次项目中Thinkphp绕过禁用函数的实战记录
2021/11/17 PHP