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

javascript

Mozilla中独有的defineGetter和defineSetter使得在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));
  };
}

时间: 2024-08-30 01:50:37

贴一个在Mozilla中常用的Javascript代码的相关文章

贴一个在Mozilla中常用的Javascript代码_基础知识

Mozilla中独有的读写器(defineGetter.defineSetter)以及可以给Element,Event等加上prototype原型,使得在IE里用的方法同样在Mozilla中可以适用,下面贴出常用的一些代码 例如 obj.insertAdjacentHTML, currentStyle, obj.attachEvent, obj.detachEvent等等. 版权属于Erik Arvidsson, webfx 复制代码 代码如下: if (Browser.isMozilla) {

B/S模式项目中常用的javascript汇总

 本篇文章是对B/S模式项目中常用的javascript进行了汇总介绍,需要的朋友可以过来参考下,希望对大家有所帮助 屏弊网页的右键 <body oncontextmenu="return false">或<body style="overflow-y:hidden">   为网页加入背景音乐 IE:<bgsound src="*.mid" loop=infinite> NS:<embed src=&qu

PHP开发中常用的十个代码样例_php实例

一.黑名单过滤 function is_spam($text, $file, $split = ':', $regex = false){ $handle = fopen($file, 'rb'); $contents = fread($handle, filesize($file)); fclose($handle); $lines = explode("n", $contents); $arr = array(); foreach($lines as $line){ list($w

java-怎么获取一个JAVA类中各个方法的代码块

问题描述 怎么获取一个JAVA类中各个方法的代码块 特殊需求:获取一个JAVA类中各个方法的代码块来查找方法中是否包含某个关键字,现在通过发射只能拿到方法的属性和注释,有没有API或者其他方法,求告知,3Q 没金币了..对不起大家 PS:获取本地源代码的,不是运行时的class 解决方案 myeclipse中调试调用带有静态代码块的类时出现java.lang.NoClassDefFoundError的处理方法在DWR中实现直接获取一个JAVA类的返回值的两种方法java代码获取当前类类名.方法名

Android 启动另一个App/apk中的Activity实现代码

Android 启动另一个App/apk中的Activity实现代码 前言: Android提供了在一个App中启动另一个App中的Activity的能力,这使我们的程序很容易就可以调用其他程序的功能,从而就丰富了我们App的功能.比如在微信中发送一个位置信息,对方可以点击这个位置信息启动腾讯地图并导航.这个场景在现实中作用很大,尤其是朋友在陌生的环境找不到对方时,这个功能简直就是救星. 本来想把本文的名字叫启动另一个进程中的Activity,觉得这样才有逼格.因为每个App都会运行在自己的虚拟

asp编程中常用的javascript辅助代码第1/2页_应用技巧

一些常用的辅助代码  点击返回上页代码: <form> <p><input TYPE="button" VALUE="返回上一步" ONCLICK="history.back(-1)"></p> </form> 弹出警告框代码: <form> <p><input TYPE="button" VALUE="弹出警告框" 

asp编程中常用的javascript辅助代码第1/2页

一些常用的辅助代码 点击返回上页代码: <form> <p><input TYPE="button" VALUE="返回上一步" ONCLICK="history.back(-1)"></p> </form> 弹出警告框代码: <form> <p><input TYPE="button" VALUE="弹出警告框" O

B/S模式项目中常用的javascript汇总_javascript技巧

屏弊网页的右键<body oncontextmenu="return false">或<body style="overflow-y:hidden"> 为网页加入背景音乐IE:<bgsound src="*.mid" loop=infinite>NS:<embed src="*.mid" autostart=true hidden=true loop=true></embe

程序中常用的种代码_基础应用

1. 打开新的窗口并传送参数:  传送参数: response.write("<script>window.open('*.aspx?id="+this.DropDownList1.SelectIndex+"&id1="+...+"')</script>") 接收参数: string a = Request.QueryString("id"); string b = Request.QueryS