• 2008-01-23

    MDC:从Internet Explorer迁移到Mozilla(下) - [技术空间]


    从Internet Explorer迁移到Mozilla(下)

    From MDC


    [编辑] JavaScript 与 CSS

    Since Mozilla supports the CSS standards, it also supports the CSS DOM standard for setting CSS through JavaScript. You can access, remove, and change an element's CSS rules through the element's style member:

    因为Mozilla支持CSS标准,所以它也支持CSS DOM标准,可以通过JavaScript设置CSS。用户可以通过元素的style成员读取、修改或删除元素的CSS规则:

    <div id="myDiv" style="border: 1px solid black;">
      var myElm = document.getElementById("myDiv"); 
      myElm.style.width = "40px"; 

    You can reach every CSS attribute that way. Again, if the Web page is in strict mode, you must set a unit or else Mozilla will ignore the command. When you query a value, say through .style.width, in Mozilla and Internet Explorer, the returned value will contain the unit, meaning a string is returned. You can convert the string into a number through parseFloat("40px").

    用户可以用同样的方法访问所有的CSS属性。再次提醒,如果网页是strict mode,用户必须设置度量单位,否则Mozilla将忽略这行代码。用户可以用 .style.width在Mozilla和IE中查询属性值,返回值是包含度量单位在内的,也就是说返回值是string(字符串)。用户可以用parseFloat("40px")把string转换成数字。

    // 捕获鼠标移动


    document.onmousemove = mydivMoveFunc;

    // 释放鼠标移动


    document.onmousemove = null;


    // 捕获鼠标移动window.captureEvents(Event.MOUSEMOVE);

    window.onmousemove = mydivMoveFunc;

    // 释放鼠标移动


    window.onmousemove = null;

    [编辑] CSS 溢出(overflow) 的差异

    CSS added the notion of overflow, which allows you to define how to handle overflow; for example, when the contents of a div with a specified height are taller than that height. The CSS standard defines that if no overflow behavior is set in this case, the div contents will overflow. However, Internet Explorer does not comply with this and will expand the div beyond its set height in order to hold the contents. Below is an example that shows this difference:

    CSS中有overfolw(溢出)的标记,有了它,开发者可以自己决定如何处理overflow;比如,div的内容的实际高度比div定义的高 度高。CSS标准中的定义是,如果这种情况下没有设置overflow的处理代码,div的内容将溢出。然而,IE并不遵从这个定义,它为了显示全部内 容,会拉长这个div,超出原来设置的高度。下面的例子可以说明这点差异:

    <div style="height: 100px; border: 1px solid black;">
      <div style="height: 150px; border: 1px solid red; margin: 10px;">

    As you can see in Figure 4, Mozilla acts like the W3C standard specifies. The W3C standard says that, in this case, the inner div overflows to the bottom since the inner content is taller than its parent. If you prefer the Internet Explorer behavior, simply do not specify a height on the outer element.


    Figure 4. DIV overflow


    [编辑] hover 的差异

    The nonstandard CSS hover behavior in Internet Explorer occurs on quite a few web sites. It usually manifests itself by changing text style when hovered over in Mozilla, but not in Internet Explorer. This is because the a:hover CSS selector in Internet Explorer matches <a href="">...</a> but not <a name="">...</a>, which sets anchors in HTML. The text changes occur because authors encapsulate the areas with the anchor-setting markup:

    在IE中,非标准的CSS hover行为只有在少数页面中才会发生。在Mozilla中,CSS hover一般会在(鼠标)掠过其上方时,改变颜色秀出自己,但在IE中不会。这是因为IE中a:hover 的CSS选择器匹配<a href="">...</a>,但不匹配<a name="">...</a>,后者是在HTML中设置anchor(锚点或锚记)。文本发生改变是因为作者用设置anchor的标记把这个区域包围了起来:

      a:hover {color: green;}
      <a href="foo.com">This text should turn green when you hover over it.</a>
      <a name="anchor-name">
        This text should change color when hovered over, but doesn't
        in Internet Explorer.

    Mozilla follows the CSS specification correctly and will change the color to green in this example. You can use two ways to make Mozilla behave like Internet Explorer and not change the color of the text when hovered over:

    • First, you can change the CSS rule to be a:link:hover {color: green;}, which will only change the color if the element is a link (has an href attribute).
    • Alternatively, you can change the markup and close the opened <a /> before the start of the text -- the anchor will continue to work this way.


    • 一、用户可以把CSS规则改为 a:link:hover {color: green;},这样,只有元素是超链接时(有href属性),颜色才会改变。
    • 二、用户可以改变标记,在文字开始前结束<a />--这样anchor可以保留原有的功能。

    [编辑] Quirks versus standards mode/ 另类模式vs标准模式

    Older legacy browsers, such as Internet Explorer 4, rendered with so-called quirks under certain conditions. While Mozilla aims to be a standards-compliant browser, it has three modes that support older Web pages created with these quirky behaviors. The page's content and delivery determine which mode Mozilla will use. Mozilla will indicate the rendering mode in View -> Page Info (or Ctrl+I) ; Firefox will list the rendering mode in Tools -> Page Info. The mode in which a page is located depends on its doctype.

    较老的浏览器,如IE4,在一些特定的情况下,会用所谓的另类模式(quirks)显示页面。因为Mozilla的目标是一款支持标准的浏览器,所以它有三种模式,可以支持带有特有行为的老网页。页面的内容以及delvery决定着Mozilla使用那种模式。Mozilla可以用View -> Page Info (或 Ctrl+I)指示显示模式;Firefox用Tools -> Page Info列出显示模式。页面处于哪种模式由doctype(文档类型声明)决定。

    Doctypes (short for document type declarations) look like this:

    Doctype(document type declarations的缩写)如下所示:

    <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

    The section in blue is called the public identifier, the green part is the system identifier, which is a URI.


    [编辑] 标准模式

    Standards mode is the strictest rendering mode -- it will render pages per the W3C HTML and CSS specifications and will not support any quirks. Mozilla uses it for the following conditions:

    标准模式(standard mode)是最严格的显示模式——它将根据W3C HTML和CSS规范显示页面,而不支持任何特有行为。Mozilla在下面这些情况中使用该模式:

    • If a page is sent with a text/xml mimetype or any other XML or XHTML mimetype
    • For any "DOCTYPE HTML SYSTEM" doctype (for example, <!DOCTYPE HTML SYSTEM "http://www.w3.org/TR/REC-html40/strict.dtd">), except for the IBM doctype
    • For unknown doctypes or doctypes without DTDs
    1. 如果页面含有text/xml的mimetype,或者其他的XML以及XHTML的mimetype
    2. 如果doctype是 "DOCTYPE HTML SYSTEM" (例如, <!DOCTYPE HTML SYSTEM "http://www.w3.org/TR/REC-html40/strict.dtd">),但不包括IBM doctype
    3. 如果doctype未知,或doctype中没有DTD

    [编辑] 准标准模式

    Mozilla introduced almost standards mode for one reason: a section in the CSS 2 specification breaks designs based on a precise layout of small images in table cells. Instead of forming one image to the user, each small image ends up with a gap next to it. The old IBM homepage shown in Figure 5 offers an example.

    Mozilla引入了准标准模式(almost standards mode)是因为以下原因:CSS2规范中的一节破坏了基于表格的小图片精确布局的设计。不同于合成一张图片给用户,每张小图片之后都有一小段间隙。图5中的IBM旧首页就是一个例子。

    图5. 图片间隙


    Almost standards mode behaves almost exactly as standards mode, except when it comes to an image gap issue. The issue occurs often on standards-compliant pages and causes them to display incorrectly.


    Mozilla uses almost standards mode for the following conditions:


    • 对于所有的“宽松的”dictype (例如, <!DOCTYPE HTML PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN">, <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">)
    • 对于IBM doctype (<!DOCTYPE html SYSTEM "http://www.ibm.com/data/dtd/v11/ibmxhtml1-transitional.dtd">)

    You can read more about the image gap issue.

    读者可以阅读更多关于 图片间隙的话题

    [编辑] 另类(quirk)模式

    Currently, the Web is full of invalid HTML markup, as well as markup that only functions due to bugs in browsers. The old Netscape browsers, when they were the market leaders, had bugs. When Internet Explorer arrived, it mimicked those bugs in order to work with the content at that time. As newer browsers came to market, most of these original bugs, usually called quirks, were kept for backwards compatibility. Mozilla supports many of these in its quirks rendering mode. Note that due to these quirks, pages will render slower than if they were fully standards-compliant. Most Web pages are rendered under this mode.


    Mozilla uses quirks mode for the following conditions:


    • 没有定义doctype
    • doctype没有系统标识符(比如, <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">)

    For further reading, check out: Mozilla Quirks Mode Behavior and Mozilla's DOCTYPE sniffing.

    要想了解更多,请阅读 Mozilla Quirks Mode BehaviorMozilla's DOCTYPE sniffing

    [编辑] 事件差异

    Mozilla and Internet Explorer are almost completely different in the area of events. The Mozilla event model follows the W3C and Netscape model. In Internet Explorer, if a function is called from an event, it can access the event object through window.event. Mozilla passes an event object to event handlers. They must specifically pass the object on to the function called through an argument. A cross-browser event handling example follows:

    在事件(event)处理方面,可以说Mozilla与IE是完全不同。Mozilla的事件处理模型沿用了W3C和Netscape的模型。在IE中,如果函数被一个事件调用,它可以通过window.event访问event对象。而Mozilla把event对象传递给事件句柄(event handler)。它们必须用不同的参数把这个对象传递到函数中。跨浏览器的事件处理代码可能会写成这样:

    <div onclick="handleEvent(event);">Click me!</div>
      function handleEvent(aEvent) { 
        // if aEvent is null, means the Internet Explorer event model, 
        // so get window.event. 
        var myEvent = aEvent ? aEvent : window.event; 

    Sometimes this doesn't work because Internet Explorer "catches" the aEvent parameter, identifiying it as not null, making it not use window.event any longer. The solution is to simply test for the window.event property:


    <div onclick="handleEvent(event);">Click me!</div>
      function handleEvent(aEvent) { 
        var myEvent = window.event ? window.event : aEvent;

    The properties and functions that the event object exposes are also often named differently between Mozilla and Internet Explorer, as Table 4 shows.


    表4 Mozilla与IE之间的事件属性差异
    Internet Explorer Name Mozilla Name Description
    altKey altKey Boolean property that returns whether the alt key was pressed during the event.
    cancelBubble stopPropagation() Used to stop the event from bubbling farther up the tree.
    clientX clientX The X coordinate of the event, in relation to the element viewport.
    clientY clientY The Y coordinate of the event, in relation to the element viewport.
    ctrlKey ctrlKey Boolean property that returns whether the Ctrl key was pressed during the event.
    fromElement relatedTarget For mouse events, this is the element from which the mouse moved away.
    keyCode keyCode For keyboard events, this is a number representing the key that was pressed. It is 0 for mouse events.
    returnValue preventDefault() Used to prevent the event's default action from occurring.
    screenX screenX The X coordinate of the event, in relation to the screen.
    screenY screenY The Y coordinate of the event, in relation to the screen.
    offsetX layerX 获取鼠标在对像上X坐标.
    offsetY layerY 获取鼠标在对像上Y坐标.
    shiftKey shiftKey Boolean property that returns whether the Shift key was pressed during the event.
    srcElement target The element to which the event was originally dispatched.
    toElement currentTarget For mouse events, this is the element to which the mouse moved.
    type type Returns the name of the event.

    [编辑] 关联事件处理函数

    Mozilla supports two ways to attach events through JavaScript. The first, supported by all browsers, sets event properties directly on objects. To set a click event handler, a function reference is passed to the object's onclick property:


    <div id="myDiv">Click me!</div>
      function handleEvent(aEvent) {
        // if aEvent is null, means the Internet Explorer event model,
        // so get window.event.
        var myEvent = aEvent ? aEvent : window.event;
      function onPageLoad(){
        document.getElementById("myDiv").onclick = handleEvent;

    Mozilla fully supports the W3C standard way of attaching listeners to DOM nodes. You use the addEventListener() and removeEventListener() methods, and have the benefit of being able to set multiple listeners for the same event type. Both methods require three parameters: the event type, a function reference, and a boolean denoting whether the listener should catch events in their capture phase. If the boolean is set to false, it will only catch bubbling events. W3C events have three phases: capturing, at target, and bubbling. Every event object has an eventPhase attribute indicating the phase numerically (0 indexed). Every time you trigger an event, the event starts at the DOM's outermost element, the element at the top of the DOM tree. It then walks the DOM using the most direct route toward the target, which is the capturing phase. When the event reaches the target, the event is in the target phase. After arriving at the target, it walks up the DOM tree back to the outermost node; this is bubbling. Internet Explorer's event model only has the bubbling phase; therefore, setting the third parameter to false results in Internet Explorer-like behavior:

    Mozilla支持W3C标准定义的添加linstener给DOM节点的所有方法。用户可以使用addEventListener()removeEventListener() 函数,也可以向同一个event type(事件类型)添加多个listener。两个函数都需要三个参数:event type(事件类型),function reference(函数引用),和一个标识listener在捕获阶段(capture phase)是否捕获事件的boolean(布尔值)。如果boolean参数设为false,它将只捕获bubbling event。W3C对event定义了三个阶段:capturing,at target,和bubbling。每个event对象都有eventPhase属性,以数字表明所处的阶段(索引从0开始)。每当event被触发时,event从DOM最外层的元素(在DOM 树型结构最顶端的元素)开始,然后它沿着最短的路径向target(目标节点)遍历,这就是捕获阶段。当事件到达目标节点, 事件就转到目标节点阶段。到达目标节点之后,它就沿着DOM树上溯到最外层的节点;这个过程就是冒泡(bubling)。IE的事件模型(event model)只支持冒泡阶段,所以,把第三个参数设为false就会得到与IE的相似行为:

    <div id="myDiv">Click me!</div> 
      function handleEvent(aEvent) {
        // if aEvent is null, it is the Internet Explorer event model,
        // so get window.event.
        var myEvent = aEvent ? aEvent : window.event;
      function onPageLoad() {
        var element = document.getElementById("myDiv");
        element.addEventListener("click", handleEvent, false);

    One advantage of addEventListener() and removeEventListener() over setting properties is that you can have multiple event listeners for the same event, each calling another function. Thus, to remove an event listener requires all three parameters be the same as the ones you use when adding the listener.

    和设置属性相比,addEventListener()和removeEventListener()的优势在于,对同一个event可以有多个 event listener,每一个都是调用不同的函数。因此,删除一个event listener时,要求三个参数与添加listener时的三个参数完全相同。

    Mozilla does not support Internet Explorer's method of converting <script> tags into event handlers, which extends <script> with for and event attributes (see Table 5). It also does not support the attachEvent and detachEvent methods. Instead, you should use the addEventListener and removeEventListener methods. Internet Explorer does not support the W3C events specification.

    Mozilla不支持IE中把<script>标签转换为event handler的方法——IE用for和event属性对<script>进行了扩展(参加表5)。它用样不支持attachEvent和 detachEvent方法。用户应该使用addEventListener和removeEventListener方法。IE不支持W3C的 event规范。

    表5 Mozilla与IE之间事件方法的差异
    Internet Explorer Method Mozilla Method Description
    attachEvent(aEventType, aFunctionReference) addEventListener(aEventType, aFunctionReference, aUseCapture) Adds an event listener to a DOM element.
    detachEvent(aEventType, aFunctionReference) removeEventListener(aEventType, aFunctionReference, aUseCapture) Removes an event listener to a DOM element.

    [编辑] 富文本编辑

    While Mozilla prides itself with being the most W3C web standards compliant browser, it does support nonstandard functionality, such as innerHTML and rich text editing, if no W3C equivalent exists.

    在Mozilla作为对W3C web标准支持最好的浏览器的同时,它也支持非标准的功能,比如innerHTML 和富文本编辑rich text editing, 前提是没有相应的W3C规范。

    Mozilla 1.3 introduced an implementation of Internet Explorer's designMode feature, which turns an HTML document into a rich text editor field. Once turned into the editor, commands can run on the document through the execCommand command. Mozilla does not support Internet Explorer's contentEditable attribute for making any widget editable. You can use an iframe to add a rich text editor.

    Mozilla1.3引入了IE中designMode功能,它可以把HTML文档转换为富文本编辑区域 ,各种指令可以通过execCommand命令在document中执行。Mozilla不支持IE中把所有控件都变为可编辑状态(editable)的contentEditable属性。但用户可以用iframe添加富文本编辑。

    [编辑] 富文本差异

    Mozilla supports the W3C standard of accessing iframe's document object through IFrameElmRef.contentDocument, while Internet Explorer requires you to access it through document.frames["IframeName"] and then access the resulting document:


    function getIFrameDocument(aID) {
      var rv = null; 
      // if contentDocument exists, W3C compliant (Mozilla)
      if (document.getElementById(aID).contentDocument){
        rv = document.getElementById(aID).contentDocument;
      } else {
        // IE
        rv = document.frames[aID].document;
      return rv;

    Another difference between Mozilla and Internet Explorer is the HTML that the rich text editor creates. Mozilla defaults to using CSS for the generated markup. However, Mozilla allows you to toggle between HTML and CSS mode using the useCSS execCommand and toggling it between true and false. Internet Explorer always uses HTML markup.

    Mozilla与IE间的另一个差别是富文本编辑生成的HTML不同。 Mozilla默认使用CSS标记。当然,Mozilla也允许用户在execCommand中用useCSS进行HTML与CSS模式的切换。而IE只使用HTML标记。

    Mozilla (CSS): 
      <span style="color: blue;">Big Blue</span> 
    Mozilla (HTML): 
      <font color="blue">Big Blue</font> 
    Internet Explorer: 
      <FONT color="blue">Big Blue</FONT> 

    Below is a list of commands that execCommand in Mozilla supports:


    Table 6. Rich text editing commands
    Command Name Description Argument
    bold Toggles the selection's bold attribute. ---
    createlink Generates an HTML link from the selected text. The URL to use for the link
    delete Deletes the selection. ---
    fontname Changes the font used in the selected text. The font name to use (Arial, for example)
    fontsize Changes the font size used in the selected text. The font size to use
    fontcolor Changes the font color used in the selected text. The color to use
    indent Indents the block where the caret is. ---
    inserthorizontalrule Inserts an <hr> element at the cursor's position. ---
    insertimage Inserts an image at the cursor's position. URL of the image to use
    insertorderedlist Inserts an ordered list (<ol>) element at the cursor's position. ---
    insertunorderedlist Inserts an unordered list (<ul>) element at the cursor's position. ---
    italic Toggles the selection's italicize attribute. ---
    justifycenter Centers the content at the current line. ---
    justifyleft Justifies the content at the current line to the left. ---
    justifyright Justifies the content at the current line to the right. ---
    outdent Outdents the block where the caret is. ---
    redo Redoes the previous undo command. ---
    removeformat Removes all formatting from the selection. ---
    selectall Selects everything in the rich text editor. ---
    strikethrough Toggles the strikethrough of the selected text. ---
    subscript Converts the current selection into subscript. ---
    superscript Converts the current selection into superscript. ---
    underline Toggles the underline of the selected text. ---
    undo Undoes the last executed command. ---
    unlink Removes all link information from the selection. ---
    useCSS Toggles the usage of CSS in the generated markup. Boolean value

    For more information, visit Rich-Text Editing in Mozilla.

    想了解更多信息,请参见Rich-Text Editing in Mozilla

    [编辑] XML差异

    Mozilla has strong support for XML and XML-related technologies, such as XSLT and Web services. It also supports some nonstandard Internet Explorer extensions, such as XMLHttpRequest.

    Mozilla对XML以及与XML相关的技术提供强有力的支持,比如XSLT和Web services。它也支持一些非标准的IE扩展,比如XMLHttpRequest。

    (tick.huang@gmail.com end @ 2006.11.8)

    [编辑] 如何处理XML

    As with standard HTML, Mozilla supports the W3C XML DOM specification, which allows you to manipulate almost any aspect of an XML document. Differences between Internet Explorer's XML DOM and Mozilla are usually caused by Internet Explorer's nonstandard behaviors. Probably the most common difference is how they handle white space text nodes. Often when XML generates, it contains white spaces between XML nodes. Internet Explorer, when using XMLNode.childNodes[], will not contain these white space nodes. In Mozilla, those nodes will be in the array.

    就像支持标准的HTML一样,Mozilla同样支持W3C XML DOM的规范,这使用户可以对XML文档进行多种多样的操作。IE与Mozilla之间的XML DOM差异通常是有IE的非标准行为引起的。也许最常见的差异就是它们如何处理文本节点(译注:text node,指<.../>或<...>...</....>之外的文件内容,包括空格、回车等)的空白符(译注:空格、制表符等)。通常,生成XML时,在XML节点间会有空白符。IE调用XMLNode.childNodes[]时,在结果中不会包含这些是空白符的节点。而Mozilla中,这些空节点会在数组中。

      <?xml version="1.0"?> 
      <myXMLdoc xmlns:myns="http://myfoo.com"> 
      var myXMLDoc = getXMLDocument().documentElement; 

    The first line of JavaScript loads the XML document and accesses the root element (myXMLDoc) by retrieving the documentElement. The second line simply alerts the number of child nodes. Per the W3C specification, the white spaces and new lines merge into one text node if they follow each other. For Mozilla, the myXMLdoc node has three children: a text node containing a new line and two spaces; the myns:foo node; and another text node with a new line. Internet Explorer, however, does not abide by this and will return "1" for the above code, namely only the myns:foo node. Therefore, to walk the child nodes and disregard text nodes, you must distinguish such nodes.

    第一行JavaScript代码加载XML document并通过documentElement获取根元素(myXMLDoc)。 第二行代码只是简单的显示子节点的个数。根据W3C规范,如果空格和回车相邻,它们将被合并成一个文本节点(text node)。对于Mozilla,myXMLdoc节点有三个子节点:第一个节点有一个回车和两个空格;第二个节点是myns:foo;第三个节点有一个 回车。而IE没有遵守这个规范,上面的这段代码将返回“1”,也就是说只有myns:foo节点。所以,遍历子节点以及是否忽略文本节点(text node),用户需要区分对待。

    As mentioned earlier, every node has a nodeType attribute representing the node type. For example, an element node has type 1, while a document node has type 9. To disregard text nodes, you must check for types 3 (text node) and 8 (comment node).

    在前面已经提过,每个节点有个nodeType属性标识节点的类型。比如,元素节点(element node)的类型是1,文档节点(document node)的类型是9。要忽略text node,需要判断类型3(文本节点)和8(注释节点)。

      <?xml version="1.0"?>   
      <myXMLdoc xmlns:myns="http://myfoo.com"> 
      var myXMLDoc = getXMLDocument().documentElement; 
      var myChildren = myXMLDoc.childNodes; 
      for (var run = 0; run < myChildren.length; run++){ 
        if ( (myChildren[run].nodeType != 3) &&
              myChildren[run].nodeType != 8) ){ 
          // 不是文本节点或注释节点

    [编辑] XML data islands

    Internet Explorer has a nonstandard feature called XML data islands, which allow you to embed XML inside an HTML document using the nonstandard HTML tag <xml>. Mozilla does not support XML data islands and handles them as unknown HTML tags. You can achieve the same functionality using XHTML; however, because Internet Explorer's support for XHTML is weak, this is usually not an option.

    IE有个非标准的特性,被称为XML data islands,它允许用户在HTML文档中使用HTML的标记<xml> 嵌入XML。Mozilla不支持XML data island,就把它当作未知的HTML标记来处理。 用户可以使用XHTML实现相同的功能;但是,因为IE对XHTML的支持比较弱,所以通常不推荐这种方法。

    One cross-browser solution is to use DOM parsers, which parse a string that contains a serialized XML document and generates the document for the parsed XML. Mozilla uses the DOMParser class, which takes the serialized string and creates an XML document out of it. In Internet Explorer, you can achieve the same functionality using ActiveX. A new Microsoft.XMLDOM generates and has a loadXML method that can take in a string and generate a document from it. The following code shows you how:

    一个跨浏览器的解决办法是使用DOM解析器,它可以解析内容是序列化的(serialized)XML文档的string,然后生成文档。 Mozilla使用DOMParser类,它以序列化的string作为输入,生成XML文档。在IE中,用户可以使用ActiveX实现相同的功能。Microsoft.XMLDOM有个方法loadXML,它以string作为输入,生成文档。下面的代码演示了如何实现:

    IE XML data island: 
      <xml id="xmldataisland"> 
    Cross-browser solution: 
      var xmlString = "<xml id=\"xmldataisland\"><foo>bar</foo></xml>"; 
      var myDocument; 
      if (document.implementation.createDocument){ 
        // Mozilla,创建DOMParser
        var parser = new DOMParser(); 
        myDocument = parser.parseFromString(xmlString, "text/xml"); 
      } else if (window.ActiveXObject){ 
        // IE,用ActiveX创建XML document,然后把loadXML当作DOM解析器来用
        myDocument = new ActiveXObject("Microsoft.XMLDOM"); 

    [编辑] XML HTTP请求

    Internet Explorer allows you to send and retrieve XML files using MSXML's XMLHTTP class, which is instantiated through ActiveX using new ActiveXObject("Msxml2.XMLHTTP") or new ActiveXObject("Microsoft.XMLHTTP"). Since there is no standard method of doing this, Mozilla provides the same functionality in the global JavaScript XMLHttpRequest object. The object generates asynchronous requests by default.

    IE允许用户使用MSXML的XMLHTTP类发送和接受XML文件,这个类通过调用new ActiveXObject("Msxml2.XMLHTTP")new ActiveXObject("Microsoft.XMLHTTP")进行实例化。因为不存在具有此功能的标准函数,所以Mozilla在全局的JavaScript对象XMLHttpRequest中提供了相同的功能。该对象默认生成异步的请求。

    After instantiating the object using new XMLHttpRequest(), you can use the open method to specify what type of request (GET or POST) you use, which file you load, and if it is asynchronous or not. If the call is asynchronous, then give the onload member a function reference, which is called once the request has completed.

    使用new XMLHttpRequest()实例化对象后,用户可以使用open 函数指定请求的类型(GET或POST)、要加载的文件、以及是否为异步调用。如果是异步调用,需要给onload成员一个函数引用,请求一完成,这个函数就会被调用。


      var myXMLHTTPRequest = new XMLHttpRequest(); 
      myXMLHTTPRequest.open("GET", "data.xml", false); 
      var myXMLDocument = myXMLHTTPRequest.responseXML; 


      var myXMLHTTPRequest; 
      function xmlLoaded() { 
        var myXMLDocument = myXMLHTTPRequest.responseXML; 
      function loadXML(){ 
        myXMLHTTPRequest = new XMLHttpRequest();
        myXMLHTTPRequest.open("GET", "data.xml", true);
        myXMLHTTPRequest.onload = xmlLoaded; 

    Table 7 features a list of available methods and properties for Mozilla's XMLHttpRequest.


    Table 7. XMLHttpRequest methods and properties
    void abort()Stops the request if it is still running.
    string getAllResponseHeaders()Returns all response headers as one string.
    string getResponseHeader(string headerName)Returns the value of the specified header.
    functionRef onerrorIf set, the references function will be called whenever an error occurs during the request.
    functionRef onloadIf set, the references function will be called when the request completes successfully and the response has been received. Use when an asynchronous request is used.
    void open (string HTTP_Method, string URL)

    void open (string HTTP_Method, string URL, boolean async, string userName, string password)
    Initializes the request for the specified URL, using either GET or POST as the HTTP method. To send the request, call the send() method after initialization. If async is false, the request is synchronous, else it defaults to asynchronous. Optionally, you can specify a username and password for the given URL needed.
    int readyStateState of the request. Possible values:
    0UNINITIALIZED - open() has not been called yet.
    1LOADING - send() has not been called yet.
    2LOADED - send() has been called, headers and status are available.
    3INTERACTIVE - Downloading, responseText holds the partial data.
    4COMPLETED - Finished with all operations.
    string responseTextString containing the response.
    DOMDocument responseXMLDOM Document containing the response.
    void send(variant body)Initiates the request. If body is defined, it issent as the body of the POST request. body can be an XML document or a string serialized XML document.
    void setRequestHeader (string headerName, string headerValue)Sets an HTTP request header for use in the HTTP request. Has to be called after open() is called.
    string statusThe status code of the HTTP response.

    [编辑] XSLT差异

    Mozilla supports XSL Transformations (XSLT) 1.0. It also allows JavaScript to perform XSLT transformations and allows running XPATH on a document.

    Mozilla支持XSLT 1.0( XSL Transformations)。它也允许JavaScript执行XSLT转换,和对document运行XPATH。

    Mozilla requires that you send the XML and XSLT file holding the stylesheet with an XML mimetype (text/xml or application/xml). This is the most common reason why XSLT won't run in Mozilla but will in Internet Explorer. Mozilla is strict in that way.

    Mozilla要求用户发送含有stylesheet的XML和XSLT文件时要有mimetype XML(text/xml or application/xml)。Mozilla对此要求很严格。这就是为什么XSLT不能在Mozilla中运行而能在IE中运行的最常见的原因。

    Internet Explorer 5.0 and 5.5 supported XSLT's working draft, which is substantially different than the final 1.0 recommendation. The easiest way to distinguish what version an XSLT file was written against is to look at the namespace. The namespace for the 1.0 recommendation is http://www.w3.org/1999/XSL/Transform, while the working draft's namespace is http://www.w3.org/TR/WD-xsl. Internet Explorer 6 supports the working draft for backwards compatibility, but Mozilla does not support the working draft, only the final recommendation.

    IE5.0和5.5支持XSLT的工作草案(working draft),这个工作草案和1.0最终推荐版(final 1.0 recommendation)之间有很大的差异。区分XSLT文件版本的最简单的方法是查看命名空间(namespace)。1.0推荐版的命名空间是http://www.w3.org/1999/XSL/Transform,而working draft的命名空间是http://www.w3.org/TR/WD-xsl。 IE6为了兼容性,支持工作草案;但是Mozilla不支持工作草案,它只支持最终推荐版。

    If XSLT requires you to distinguish the browser, you can query the "xsl:vendor" system property. Mozilla's XSLT engine will report itself as "Transformiix" and Internet Explorer will return "Microsoft."


    <xsl:if test="system-property('xsl:vendor') = 'Transformiix'"> 
      <!-- Mozilla specific markup --> 
    <xsl:if test="system-property('xsl:vendor') = 'Microsoft'"> 
      <!-- Internet Explorer specific markup --> 

    Mozilla also provides JavaScript interfaces for XSLT, allowing a Web site to complete XSLT transformations in memory. You can do this using the global XSLTProcessor JavaScript object. XSLTProcessor requires you to load the XML and XSLT files, because it needs their DOM documents. The XSLT document, imported by the XSLTProcessor, allows you to manipulate XSLT parameters. XSLTProcessor can generate a standalone document using transformToDocument(), or it can create a document fragment using transformToFragment(), which you can easily append into another DOM document. Below is an example:

    Mozilla提供了JavaScript接口,允许网站在内存中完成XSLT的转换。用户可以使用全局的JavaScript对象XSLTProcessorXSLTProcessor要求用户机咱XML和XSLT文件,因为它需要它们的DOM document。由XSLTProcessor加载(import)的XSLT document允许用户对XSLT参数进行操作。XSLTProcessor可以通过transformToDocument()生成独立的document,它也能通过 transformToFragment()生成document fragment,这让用户可以很方便地将其添加到别的DOM document。下面举个例子:

    var xslStylesheet; 
    var xsltProcessor = new XSLTProcessor(); 
    // 加载xslt文件“example1.xsl”
    var myXMLHTTPRequest = new XMLHttpRequest(); 
    myXMLHTTPRequest.open("GET", "example1.xsl", false); 
    // 获取XML cocument并加载它
    xslStylesheet = myXMLHTTPRequest.responseXML; 
    // 加载xmlwenj“example1.xml”
    myXMLHTTPRequest = new XMLHttpRequest(); 
    myXMLHTTPRequest.open("GET", "example1.xml", false); 
    var xmlSource = myXMLHTTPRequest.responseXML; 
    var resultDocument = xsltProcessor.transformToDocument(xmlSource); 

    After creating an XSLTProcessor, you load the XSLT file using XMLHttpRequest. The XMLHttpRequest's responseXML member contains the XML document of the XSLT file, which is passed to importStylesheet. You then use the XMLHttpRequest again to load the source XML document that must be transformed; that document is then passed to the transformToDocument method of XSLTProcessor. Table 8 features a list of XSLTProcessor methods.

    创建XSLTProcessor之后,用户就可以用XMLHttpRequest()加载XSLT文件。XMLHttpRequest的成员变量responseXML的内容是对应这个XSLT文件的XML document,其中responseXML被传递给importStylesheet。之后用户再次使用XMLHttpRequest加载需要转换的XML文件,然后该文件被传递给XSLTProcessortransformToDocument函数。表8列出了XSLTProcessor的函数。

    Table 8. XSLTProcessor methods
    void importStylesheet(Node styleSheet)Imports the XSLT stylesheet. The styleSheet argument is the root node of an XSLT stylesheet's DOM document.
    DocumentFragment transformToFragment(Node source, Document owner)Transforms the Node source by applying the stylesheet imported using the importStylesheet method and generates a DocumentFragment. owner specifies what DOM document the DocumentFragment should belong to, making it appendable to that DOM document.
    Document transformToDocument(Node source)Transforms the Node source by applying the stylesheet imported using the importStylesheet method and returns a standalone DOM document.
    void setParameter(String namespaceURI, String localName, Variant value)Sets a parameter in the imported XSLT stylesheet.
    Variant getParameter(String namespaceURI, String localName)Gets the value of a parameter in the imported XSLT stylesheet.
    void removeParameter(String namespaceURI, String localName)Removes all set parameters from the imported XSLT stylesheet and makes them default to the XSLT-defined defaults.
    void clearParameters()Removes all set parameters and sets them to defaults specified in the XSLT stylesheet.
    void reset()Removes all parameters and stylesheets.

    [编辑] 该篇文章原始文件信息