贴一个在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之解决IE下不渲染的bug
Jun 29 Javascript
浅谈Javascript中Object与Function对象
Sep 26 Javascript
form表单转Json提交的方法(推荐)
Sep 23 Javascript
解析js如何获取css样式
Dec 11 Javascript
Vue.js实现一个todo-list的上移下移删除功能
Jun 26 Javascript
详解vue-cli中的ESlint配置文件eslintrc.js
Sep 25 Javascript
使用D3.js+Vue实现一个简单的柱形图
Aug 05 Javascript
nuxt中使用路由守卫的方法步骤
Jan 27 Javascript
移动端 Vue+Vant 的Uploader 实现上传、压缩、旋转图片功能
Jun 10 Javascript
JavaScript实现轮播图特效
Apr 10 Javascript
通过实例解析vuejs如何实现调试代码
Jul 16 Javascript
vue中destroyed方法的使用说明
Jul 21 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 MessagePack介绍
2013/10/06 PHP
php多个文件及图片上传实例详解
2014/11/10 PHP
PHP日志LOG类定义与用法示例
2018/09/06 PHP
vmware linux系统安装最新的php7图解
2019/04/14 PHP
简介JavaScript中substring()方法的使用
2015/06/06 Javascript
javascript禁止访客复制网页内容的实现代码
2015/08/05 Javascript
AngularJS中的表单简单入门
2016/07/28 Javascript
讲解vue-router之什么是编程式路由
2018/05/28 Javascript
Bootstrap 模态框自定义点击和关闭事件详解
2018/08/10 Javascript
Node.js连接Sql Server 2008及数据层封装详解
2018/08/27 Javascript
p5.js临摹动态图形实现方法详解
2019/10/23 Javascript
解决vue使用vant下拉框van-dropdown-item 绑定title值不变问题
2020/08/05 Javascript
vue中选中多个选项并且改变选中的样式的实例代码
2020/09/16 Javascript
python将多个文本文件合并为一个文本的代码(便于搜索)
2011/03/13 Python
wxpython学习笔记(推荐查看)
2014/06/09 Python
记录Django开发心得
2014/07/16 Python
python实现带验证码网站的自动登陆实现代码
2015/01/12 Python
Python操作SQLite数据库的方法详解
2017/06/16 Python
Python学习之Anaconda的使用与配置方法
2018/01/04 Python
Django 导出项目依赖库到 requirements.txt过程解析
2019/08/23 Python
python global关键字的用法详解
2019/09/05 Python
Python猴子补丁Monkey Patch用法实例解析
2020/03/23 Python
Python响应对象text属性乱码解决方案
2020/03/31 Python
CSS Grid布局教程之浏览器开启CSS Grid Layout汇总
2014/12/30 HTML / CSS
Draper James官网:知名演员瑞茜·威瑟斯彭所创品牌
2017/10/25 全球购物
欧洲最大的滑雪假期供应商之一:Sunweb Holidays
2018/01/06 全球购物
后勤人员自我评价怎么写
2013/09/19 职场文书
竞聘演讲稿范文
2014/01/12 职场文书
机械制造专业毕业生求职信
2014/03/02 职场文书
中文专业毕业生自荐信
2014/05/24 职场文书
2014离婚协议书范文
2014/09/10 职场文书
体育运动会广播稿
2014/10/05 职场文书
会计岗位职责
2015/02/03 职场文书
投诉书格式范本
2015/07/02 职场文书
python绘制箱型图
2021/04/27 Python
关于python爬虫应用urllib库作用分析
2021/09/04 Python