贴一个在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 关闭浏览器 (不弹出提示框)
Jan 31 Javascript
深入理解JavaScript系列(7) S.O.L.I.D五大原则之开闭原则OCP
Jan 15 Javascript
JQuery中根据属性或属性值获得元素(6种情况获取方法)
Jan 17 Javascript
基于jQuery实现动态搜索显示功能
May 05 Javascript
基于Bootstrap 3 JQuery及RegExp的表单验证功能
Feb 16 Javascript
jQuery+PHP+Mysql实现抽奖程序
Apr 12 jQuery
JavaScript+HTML5实现的日期比较功能示例
Jul 12 Javascript
jquery实现的简单轮播图功能【适合新手】
Aug 17 jQuery
iSlider手机端图片滑动切换插件使用详解
Dec 24 Javascript
Vue状态模式实现窗口停靠功能(灵动、自由, 管理后台Admin界面)
Mar 06 Javascript
基于JQuery实现页面定时弹出广告
May 08 jQuery
JavaScript常用进制转换及位运算实例解析
Oct 14 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
一个ORACLE分页程序,挺实用的.
2006/10/09 PHP
Windows中安装Apache2和PHP4权威指南
2006/11/18 PHP
php数组函数序列 之shuffle()和array_rand() 随机函数使用介绍
2011/10/29 PHP
PHP 观察者模式的实现代码
2013/05/10 PHP
php导入excel文件到mysql数据库的方法
2015/01/14 PHP
PHP中如何使用session实现保存用户登录信息
2015/10/20 PHP
javascript之对系统的toFixed()方法的修正
2007/05/08 Javascript
基于jQuery的获取标签名的代码
2012/07/16 Javascript
屏蔽网页右键复制和ctrl+c复制的js代码
2013/01/04 Javascript
原生js实现跨浏览器获取鼠标按键的值
2013/04/08 Javascript
jQuery 中国省市两级联动选择附图
2014/05/14 Javascript
javascript实现倒计时N秒后网页自动跳转代码
2014/12/11 Javascript
javascript回调函数详解
2018/02/06 Javascript
vue路由对不同界面进行传参及跳转的总结
2019/04/20 Javascript
JavaScript 实现轮播图特效的示例
2020/11/05 Javascript
python list 合并连接字符串的方法
2013/03/09 Python
python中实现php的var_dump函数功能
2015/01/21 Python
python实现QQ批量登录功能
2019/06/19 Python
十分钟搞定pandas(入门教程)
2019/06/21 Python
Pytorch 计算误判率,计算准确率,计算召回率的例子
2020/01/18 Python
浅谈Tensorflow 动态双向RNN的输出问题
2020/01/20 Python
Python关于__name__属性的含义和作用详解
2020/02/19 Python
Centos7下源码安装Python3 及shell 脚本自动安装Python3的教程
2020/03/07 Python
Python3利用openpyxl读写Excel文件的方法实例
2021/02/03 Python
three.js模拟实现太阳系行星体系功能
2019/09/03 HTML / CSS
瑞典时尚耳机品牌:Urbanears
2017/07/26 全球购物
美国大码时尚女装购物网站:ELOQUII
2017/12/28 全球购物
上海方立数码笔试题
2013/10/18 面试题
人力资源专员自我评价怎么写
2013/09/19 职场文书
《狐假虎威》教学反思
2014/02/07 职场文书
校长创先争优承诺书
2014/08/30 职场文书
判缓刑人员个人思想汇报
2014/10/10 职场文书
复兴之路展览观后感
2015/06/02 职场文书
政审证明范文
2015/06/19 职场文书
星际争霸:毕姥爷vs解冻03
2022/04/01 星际争霸
python数字图像处理:图像的绘制
2022/06/28 Python