• 2008-01-23

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

    版权声明:转载时请以超链接形式标明文章原始出处和作者信息及本声明
    http://www.blogbus.com/lily64-logs/14342106.html

    从Internet Explorer迁移到Mozilla(上)

    From MDC

    转载自http://developer.mozilla.org/cn/docs/Migrate_apps_from_Internet_Explorer_to_Mozilla

    本文正在翻译中,原文请参考 Migrate apps from Internet Explorer to Mozilla

    目录

    [隐藏]

    [编辑] 简介

    当Netscape最初推出Mozilla浏览器的时候, 特别考虑对W3C标准的支持. 所以Mozilla并不对Netscape Navigator 4.x 和微软IE遗留的源码做向后支持. 例如, Mozilla不支持<layer>, 我在后面会进行讨论. 那些像IE4一样, 在W3C标准概念之前开发的浏览器遗留了很多毛病. 在这篇文章里, 我将描述Mozilla的"Quirks Mode". 这个模式对IE和其他遗留下来的浏览器提供强大的向后HTML源码兼容性.

    我还会概括一些非标准的技术. 比如XMLHttpRequest和富文本编辑那些Mozilla支持, 但到目前为止还没有W3C标准的(技术). 它们包括:

    [编辑] 基本跨浏览器编程技巧

    尽管网络标准明确存在, 不同浏览器表现还是不同 (其实, 同一浏览器在不同操作系统上也可能不一样). 很多浏览器, 包括IE, 也支持W3C之前的API, 并从没广泛地为W3C兼容的API进行支持.

    在我详细论述Mozilla和IE的不同之前, 我要先讲一下一些关于如何令网络应用程序可以扩展来对今后新的浏览器支持的基本方法.

    因为不同浏览器有时针对相同的功能, 使用不同的API, 你经常可以在源码中找到多个用来区分浏览器的if() else()的语句块. 下面这段源码是针对IE的 (只有用IE才被解析) :

    . . . 
    
    var elm; 
    
    if (ns4) 
      elm = document.layers["myID"]; 
    else if (ie4) 
      elm = document.all["myID"]
    

    上面的源码是不可扩展的, 所以如果你想让它支持某个新的浏览器, 你必须把所有类似这样的源码块更新.

    想消除每有新浏览器就要重新编写的问题, 最简单的方法就是抽取这个功能. 相比于多个if() else(), 你应该将常用任务抽取成独立的函数, 来提高效率. 这不仅让你的源码简单易读, 更简化了对新浏览器增加支持(的步骤):

    var elm = getElmById("myID"); 
    
    function getElmById(aID){ 
      var element = null; 
    
      if (isMozilla || isIE5) 
        element = document.getElementById(aID);
      else if (isNetscape4) 
        element = document.layers[aID];
      else if (isIE4) 
        element = document.all[aID];
    
      return element; 
    } 
    

    以上的代码仍然有“浏览器监听”的问题,即探测用户正在使用哪一个浏览器。浏览器监听通常通过用户代理完成,例如:

    Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.5) Gecko/20031016 
    

    使用用户代理监听浏览器提供了使用中的浏览器的详细信息,然而当浏览器的新版本来临时,处理用户代理的代码经常出错,这样就需要修改代码。

    如果浏览器的种类无关紧要(假设你已经阻止了不被支持的浏览器访问网络应用),使用浏览器的能力或对象的特色支持来进行监听更好也更可靠。你通常可以JavaScript中测试必需的功能来做到这一点。例如,比起以下的代码:

    if (isMozilla || isIE5) 
    

    你将更愿意使用:

    if (document.getElementById) 
    

    这将允许支持W3C标准规范的浏览器(例如Opera或Safari)无须改动地工作。

    然而,用户代理监听只有在精确度显得重要时才有意义,例如在你审核一个浏览器是否符合网络应用程序的版本要求或试图解决bug的情况下。

    JavaScript也允许顺序条件语言(inline conditional statements)以助于代码的可读性:

    var foo = (condition) ? conditionIsTrue : conditionIsFalse; 
    

    例如,你可以使用以下代码来取回一个单元(element):

     
    function getElement(aID){ 
      return (document.getElementById) ? document.getElementById(aID)
                                       : document.all[aID];
    } 
    

    [编辑] Mozilla和Internet Explorer的区别

    首先,我要讨论HTML在Mozilla和Internet Explorer中表现的区别。

    [编辑] 工具提示(Tooltips)

    传统浏览器将工具提示引进HTML中,在链接上显示它们,并使用alt属性的值作为工具提示的内容。最新的W3C HTML规范创造了title属性,意欲包含链接的详细描述。现代浏览器将使用title属性来显示工具提示,且Mozilla只支持为此属性显示工具提示而不支持alt属性。

    [编辑] 实体(Entities)

    HTML markup can contain several entities, which the W3C web standards body has defined. You can reference entities through their numerical or character reference. For example, you can reference the white space character #160 with &#160; or with its equivalent character reference &nbsp;.

    HTML 置标包含了W3C 网页标准体定义的几个标准。你可以通过引用数字或字符来引用实体。例如,你可以使用&#160;以引用白色空格字符#160;或使用它的等价字符引用&nbsp;

    Some older browsers, such as Internet Explorer, had such quirks as allowing you to use entities by replacing the ; (semi-colon) character at the end with regular text content:

    某些旧式浏览器如Internet Explorer,有这样的惯例,即允许在常规文本内容末尾替换;(分号)字符以使用实体:

    &nbsp Foo 
    &nbsp&nbsp Foo 
    

    Mozilla will render the above &nbsp as white spaces, even though that is against the W3C specification. The browser will not parse a &nbsp if it is directly followed by more characters, for example:

    Mozilla提供上述&nbsp作为白色空格,即便这违反了W3C规范。如果&nbsp后直接连着更多的字符,浏览器不会解析此代码,例如:

    &nbsp12345 
    

    This code does not work in Mozilla, since it goes against the W3C web standards. Always use the correct form (&nbsp;) to avoid browser discrepancies.

    这段代码在Mozilla中无效,因为它违反了W3C标准。请始终使用正确的格式(&nbsp;) 以避免浏览器不兼容。

    [编辑] 文档对象模型(DOM)差异

    The Document Object Model (DOM) is the tree structure that contains the document elements. You can manipulate it through JavaScript APIs, which the W3C has standardized. However, prior to W3C standardization, Netscape 4 and Internet Explorer 4 implemented the APIs similarly. Mozilla only implements legacy APIs if they are unachievable with W3C web standards.
    文档对象模型(DOM)通常就是包含所有文档元素的树型结构体。开发者可以用一些javascript API来控制这个结构体,当然这些API是基于W3C标准的。在W3C标准公布前Netscape 4和IE 4 就实现了相似的功能,而Mozilla仅仅实现了一些没有成为最终标准的API。

    文档对象模型(DOM)通常就是包含所有文档元素的树型结构体。开发者可以用一些javascript API来操作这个结构体,当然这些API是W3C标准化过的。在W3C标准公布前,Netscape 4和IE 4 就已经编写了相似的API;Mozilla根据W3C标准重写了API,只有那些在W3C中没有定义的API,Mozilla才将其保留了下来。

    [编辑] 存取单元

    To retrieve an element reference using the cross-browser approach, you use document.getElementById(aID), which works in Internet Explorer 5.0+, Mozilla-based browsers, other W3C-compliant browsers and is part of the DOM Level 1 specification.

    为通过跨浏览器途径检索单元引用,你可以使用document.getElementById(aID),它是DOM Level 1 规范的一部分,并在Internet Explorer 5.0+,基于Mozilla的浏览器,以及其它适用W3C标准的浏览器中起作用。

    Mozilla does not support accessing an element through document.elementName or even through the element's name, which Internet Explorer does (also called global namespace polluting). Mozilla also does not support the Netscape 4 document.layers method and Internet Explorer's document.all. While document.getElementById lets you retrieve one element, you can also use document.layers and document.all to obtain a list of all document elements with a certain tag name, such as all <div> elements.

    Mozilla不支持通过document.elementName抑或通过单元名称存取单元,而Internet Explorer 支持(也被称为全球名称空间污染)。Mozilla也不支持Netscape 4 document.layers方法和Internet Explorer的document.all.。在通过document.getElementById索引单元的同时,你也可以使用document.layersdocument.all以获取带有特定标签名的所有文件单元列表,例如所有<div> 单元。

    The W3C DOM Level 1 method gets references to all elements with the same tag name through getElementsByTagName(). The method returns an array in JavaScript, and can be called on the document element or other nodes to search only their subtree. To get an array of all elements in the DOM tree, you can use getElementsByTagName("*").

    W3C DOM Level 1 程序通过getElementsByTagName()获取对所有标签名相同单元的索引。这种程序以Java脚本返回一个数组,并可被 document单元或其它节点访问以查找它们自己的子树。你可以使用getElementsByTagName("*")以获取DOM树中所有单元的阵列。

    The DOM Level 1 methods, as shown in Table 1, are commonly used to move an element to a certain position and toggle its visibility (menus, animations). Netscape 4 used the <layer> tag, which Mozilla does not support, as an HTML element that can be positioned anywhere. In Mozilla, you can position any element using the <div> tag, which Internet Explorer uses as well and which you'll find in the HTML specification.

    DOM Level 1 程序(见表1)通常被用来移动单元到一个特定的位置并切换它的可视度(菜单,动画等)。Netscape 4 用Mozilla不支持的<layer>标签作为可被任意放置的HTML单元。在Mozilla中,你可以使用<div>标签来放置任何单元,正如你在HTML规范中所见,它也同样被Internet Explorer 使用。

    表1. 存取单元的程序
    程序 描述
    document.getElementById( aId ) 对指定ID的单元返回索引。
    document.getElementsByTagName( aTagName ) 对指定文档中名称的单元返回数组。

    [编辑] 跨越DOM

    Mozilla supports the W3C DOM APIs for traversing the DOM tree through JavaScript (see Table 2). The APIs exist for each node in the document and allow walking the tree in any direction. Internet Explorer supports these APIs as well, but it also supports its legacy APIs for walking a DOM tree, such as the children property.

    为通过Javascript跨越DOM树型,Mozilla支持W3C DOM的应用编程接口(API) (见表2)。这种API存在于每一个文档节点中,并允许在树形中沿任意方向行走。Internet Explorer同样支持这些API,不过它也支持自己继承的API以进行树形行走,例如children属性。

    表2. 跨越DOM的程序
    属性/程序 描述
    childNodes Returns an array of all child nodes of the element.返回单元中所有子节点的数组。
    firstChild Returns the first child node of the element.返回单元中第一个子节点。
    getAttribute( aAttributeName ) Returns the value for the specified attribute.返回指定属性的值。
    hasAttribute( aAttributeName ) Returns a boolean stating if the current node has an attribute defined with the specified name.若当前节点有定义为指定名称的属性则返回布尔状态。
    hasChildNodes() Returns a boolean stating whether the current node has any child nodes.无论当前节点有无子节点,返回布尔状态。
    lastChild Returns the last child node of the element.返回单元中最后一个子节点。
    nextSibling Returns the node immediately following the current one.返回紧接当前的节点。
    nodeName Returns the name of the current node as a string.以字符串形式返回当前节点的名称。
    nodeType Returns the type of the current node.返回当前节点的类型。
    描述
    1 Element Node 单元节点
    2 Attribute Node 属性节点
    3 Text Node 文本节点
    4 CDATA Section Node CDATA选择节点
    5 Entity Reference Node 实体索引节点
    6 Entity Node 实体节点
    7 Processing Instruction Node 进程中的指示节点
    8 Comment Node 注释节点
    9 Document Node 文档节点
    10 Document Type Node 文档类型节点
    11 Document Fragment Node 文档碎片节点
    12 Notation Node 符号节点
    nodeValue Returns the value of the current node. For nodes that contain text, such as text and comment nodes, it will return their string value. For attribute nodes, the attribute value is returned. For all other nodes, null is returned.

    返回当前节点的值。对包含文本的节点,例如文本节点和注释节点,将返回它们的字符串值。对属性节点则返回属性值。对其它所有节点返回null

    ownerDocument Returns the document object containing the current node.返回包含当前节点的document对象。
    parentNode Returns the parent node of the current node.返回当前节点的母节点。
    previousSibling Returns the node immediately preceding the current one.返回当前节点的前一个节点。
    removeAttribute( aName ) Removes the specified attribute from the current node.移除当前节点中的指定属性。
    setAttribute( aName, aValue ) Sets the value of the specified attribute with the specified value.将指定属性设置为指定值。

    Internet Explorer has a nonstandard quirk, where many of these APIs will skip white space text nodes that are generated, for example, by new line characters. Mozilla will not skip these, so sometimes you need to distinguish these nodes. Every node has a nodeType property specifying the node type. For example, an element node has type 1, while a text node has type 3 and a comment node is type 8. The best way to only process element nodes is to iterate over all child nodes and only process those with a nodeType of 1:

    Internet Explorer有个非标准的例外,即许多这些API会跳过生成的白色空格文本节点(到新一行的字符,比方说)。Mozilla则不会跳过,所以有时你需要分清这些节点。每个节点都有一个nodeType属性,标明了节点的类型,例如,单元节点是1型,而一个文本节点是3型,注释节点是8型。只处理单元节点的最好方法就是循环所有子节点而唯独处理其中1型的:

    HTML: 
      <div id="foo">
        <span>Test</span>
      </div>
    
    JavaScript: 
      var myDiv = document.getElementById("foo"); 
      var myChildren = myXMLDoc.childNodes; 
      for (var i = 0; i < myChildren.length; i++) { 
        if (myChildren[i].nodeType == 1){ 
          // element node
        };
      };
    

    [编辑] 产生和操控内容

    Mozilla supports the legacy methods for adding content into the DOM dynamically, such as document.write, document.open and document.close. Mozilla also supports Internet Explorer's innerHTML method, which it can call on almost any node. It does not, however, support outerHTML (which adds markup around an element, and has no standard equivalent) and innerText (which sets the text value of the node, and which you can achieve in Mozilla by using textContent).

    Mozilla支持动态添加内容进DOM的旧式程序,例如document.writedocument.opendocument.close。Mozilla也支持Internet Explorer的innerHTML程序,它可以访问几乎所有节点。然而它并不支持outerHTML (添加一个单元的置标,且没有标准的等价程序)和innerText(设置节点的文本值,这可以用Mozilla中的textContent)来完成)。

    Internet Explorer has several content manipulation methods that are nonstandard and unsupported in Mozilla, including retrieving the value, inserting text and inserting elements adjacent to a node, such as getAdjacentElement and insertAdjacentHTML. Table 3 shows how the W3C standard and Mozilla manipulate content, all of which are methods of any DOM node.

    Internet Explorer有几个在Mozilla中不标准、不被支持的内容操控程序,包括取回数值,在节点附近添加文本和单元,例如getAdjacentElementinsertAdjacentHTML。表3显示了W3C标准和Mozilla是如何操控内容的,它们都是任意DOM节点的程序。

    表3. Mozilla操控内容的程序
    程序 描述
    appendChild( aNode ) Creates a new child node. Returns a reference to the new child node.创建一个新节点。返回此新节点的索引。
    cloneNode( aDeep ) Makes a copy of the node it is called on and returns the copy. If aDeep is true, it copies over the node's entire subtree.对被访问的节点制作备份并返回此备份。如果aDeep为真,则复制节点的整个子树。
    createElement( aTagName ) Creates and returns a new and parentless DOM node of the type specified by aTagName.以aTagName指定的数值创建并返回一个新的、无母节点的DOM节点。
    createTextNode( aTextValue ) Creates and returns a new and parentless DOM textnode with the data value specified by aTextValue.以aTextValue指定的数据值创建并返回一个新的、无母节点的DOM文本节点。
    insertBefore( aNewNode, aChildNode ) Inserts aNewNode before aChildNode , which must be a child of the current node.将aNewNode插入到aChildNode前(aChildNode(必须是当前节点的子节点)。
    removeChild( aChildNode ) Removes aChildNode and returns a reference to it.移除aChildNode并返回它的索引。
    replaceChild( aNewNode, aChildNode ) Replaces aChildNode with aNewNode and returns a reference to the removed node.以aNewNode替换aChildNode并返回被移除节点的索引。

    [编辑] Document fragments \ 文档片断

    For performance reasons, you can create documents in memory, rather than working on the existing document's DOM. DOM Level 1 Core introduced document fragments, which are lightweight documents that contain a subset of a normal document's interfaces. For example, getElementById does not exist, but appendChild does. You can also easily add document fragments to existing documents.

    Mozilla creates document fragments through document.createDocumentFragment(), which returns an empty document fragment.

    Internet Explorer's implementation of document fragments, however, does not comply with the W3C web standards and simply returns a regular document.

    出于性能的考虑,用户可以在内存中创建documents,而不使用已存在的文档的DOM。DOM第一级(Level 1)的核心引入了document fragments,一个包含部分document接口的轻量级documents。比如,有appendChild()而没有 getElementById()。读者也可以很方便的把document fragments添加到已存在的documents中。

    Mozilla创建document fragments时调用document.createDocumentFragment(),它返回空的document fragment。

    IE中document fragments的实现没有遵照W3C的标准,只是简单地返回普通的document。

    译者注:document fragments和document是变量类型,故不翻译。

    [编辑] JavaScript differences \ JavaScript中的差异

    Most differences between Mozilla and Internet Explorer are usually blamed on JavaScript. However, the issues usually lie in the APIs that a browser exposes to JavaScript, such as the DOM hooks. The two browsers possess few core JavaScript differences; issues encountered are often timing related.

    Mozilla与IE的差别之中,常常被责备的是JavaScript。然而,问题在于浏览器提供给JavaScript的API,比如DOM hook。两个浏览器的核心JavaScript存在一些差异;常常涉及有关时间消耗的问题。

    [编辑] JavaScript date 的差异

    The only Date difference is the getYear method. Per the ECMAScript specification (which is the specification JavaScript follows), the method is not Y2k-compliant, and running new Date().getYear() in 2004 will return "104". Per the ECMAScript specification, getYear returns the year minus 1900, originally meant to return "98" for 1998. getYear was deprecated in ECMAScript Version 3 and replaced with getFullYear(). Internet Explorer changed getYear() to work like getFullYear() and make it Y2k-compliant, while Mozilla kept the standard behavior.

    关于Date的唯一差异是getYear函数。根据ECMAScript的定义(JavaScript遵从这个定义),这个函数不是Y2k兼容的,在 2004年运行new Date().getYear()会返回“104”。根据ECMAScript的定义,getYear的返回值等于年份减去1900,例如“98”是 1998的返回值。getYear在ECMAScript第3版中被getFullYear()替代。IE修改了getYear(),工作方式和 getFullYear()相似,从而使其兼容Y2K,但是Mozilla仍保持标准的方式。

    [编辑] JavaScript execution differences \ 运行JavaScript时的差异

    Different browsers execute JavaScript differently. For example, the following code assumes that the div node already exists in the DOM by the time the script block executes:

    不同的浏览器运行JavaScript时也不相同。比如,下面的代码假设在script块执行之前,节点div已经存于与DOM中:

    ...
    <div id="foo">Loading...</div>
    
    <script> 
      document.getElementById("foo").innerHTML = "Done."; 
    </script> 
    

    However, this is not guaranteed. To be sure that all elements exist, you should use the onload event handler on the <body> tag:

    然而,这是没有保证的。要确保所有的元素都存在,用户应该在<body>标签中使用onload事件句柄(onload event handler)。

    <body onload="doFinish();"> 
    
    <div id="foo">Loading...</div> 
    
    <script> 
      function doFinish() { 
        var element = document.getElementById("foo");
        element.innerHTML = "Done."; 
      }
    </script> 
    ... 
    

    Such timing-related issues are also hardware-related -- slower systems can reveal bugs that faster systems hide. One concrete example is window.open, which opens a new window:

    像这些和时间耗费相关的话题也是和硬件相关的--较慢的系统可以揭示出较快的系统中隐藏的bug。举个具体的例子,window.open,它的功能是打开一个新的窗口:

    <script> 
      function doOpenWindow(){ 
        var myWindow = window.open("about:blank"); 
        myWindow.location.href = "http://www.ibm.com"; 
      }
    </script> 
    

    The problem with the code is that window.open is asynchronous -- it does not block the JavaScript execution until the window has finished loading. Therefore, you may execute the line after the window.open line before the new window has finished. You can deal with this by having an onload handler in the new window and then call back into the opener window (using window.opener).

    这段代码的问题在于,window.open是异步执行的--它在这个窗体加载完成之前不会阻塞JavaScript的执行。因此, window.open之后的代码有可能在新窗体加载完之前执行。用户可以用下面的方法解决这个问题:在新窗体中定义一个onload handler,然后返回到父窗体(使用window.opener)。

    [编辑] Differences in JavaScript-generating HTML \ JavaScript生成HTML代码的差异

    JavaScript can, through document.write, generate HTML on the fly from a string. The main issue here is when JavaScript, embedded inside an HTML document (thus, inside an <script> tag), generates HTML that contains a <script> tag. If the document is in strict rendering mode, it will parse the </script> inside the string as the closing tag for the enclosing <script>. The following code illustrates this best:

    通过document.write,JavaScript可以生成任意的HTML代码。这里的主要问题是,当JavaScript嵌在HTML文档(在 <script>标签中)中,生成的HTML代码中包含<script>会怎么样?如果文档(document)是strict rendering mode(严格的绘制模式),它会把字符串中的</script>当作与<script>对应的结束标签解析。下面的代码很好地说明了这种情况:

    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" 
     "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> 
    ... 
    <script> 
      document.write("<script type='text\/javascript'>alert('Hello');<\/script>") 
    </script> 
    

    Since the page is in strict mode, Mozilla's parser will see the first <script> and parse until it finds a closing tag for it, which would be the first </script>. This is because the parser has no knowledge about JavaScript (or any other language) when in strict mode. In quirks mode, the parser is aware of JavaScript when parsing (which slows it down). Internet Explorer is always in quirks mode, as it does not support true XHTML. To make this work in strict mode in Mozilla, separate the string into two parts:

    因为页面处于strict mode,Mozella的解析器读到第一个<script>,然后继续解析直到找到它的结束标签,那就是第一个</script>。这是因为在strict mode下,解析器不懂得关于JavaScript(或者其他语言)的任何知识。quirks mode下,解析器在解析时会考虑JavaScript(这会使它变慢)。IE一直在quirks mode,因此它不支持真正地XHTML。为了让类似地代码可以在Mozilla地strict mode下工作,把那个字符串拆成两部分就可以了:

    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" 
     "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> 
    ... 
    <script> 
      document.write("<script type='text\/javascript'>alert('Hello');</" + "script>") 
    </script> 
    

    [编辑] Debug JavaScript \ 调试JavaScript

    Mozilla provides several ways to debug JavaScript-related issues found in applications created for Internet Explorer. The first tool is the built-in JavaScript console, shown in Figure 1, where errors and warnings are logged. You can access it in Mozilla by going to Tools -> Web Development -> JavaScript Console or in Firefox (the standalone browser product from Mozilla) at Tools -> JavaScript Console.

    Mozilla提供了几种方法,用于调试原本为IE编写的程序中与JavaScript相关的问题。第一个工具是Mozilla自带的 JavaScript console(见图1),在那里记录了错误(errors)和警告(warning)。要打开它,在Mozilla中,点击Tools -> Web Development -> JavaScript Console;在firefox中(卓越的Mozilla浏览器),点击 Tools -> JavaScript Console(译注:firefox2.0中是Tools->Error Console)。

    Figure 1. JavaScript console

    Image:migrationguide-jsconsole.jpg

    The JavaScript console can show the full log list or just errors, warnings, and messages. The error message in Figure 1 says that at aol.com, line 95 tries to access an undefined variable called is_ns70. Clicking on the link will open Mozilla's internal view source window with the offending line highlighted.

    JavaScript console(或者Erroe console)可以显示完整的记录,或者只是错误、警告、信息 (errors, warnings, and messages)。图1中的错误信息说,在aol.com,95行试图去访问一个没有定义的变量is_ns70(at aol.com, line 95 tries to access an undefined variable called is_ns70)。单击该链接会打开Mozilla自带的源码查看窗口,高亮显示对应的代码行。 The console also allows you to evaluate JavaScript. To evaluate the entered JavaScript syntax, type in 1+1 into the input field and press Evaluate, as Figure 2 shows.

    在console中也可以计算JavaScript表达式的值。要计算JavaScript表达式,在输入框中输入1+1然后点击Evaluate(计算),如图2所示。

    Figure 2. JavaScript console evaluating

    Image:migrationguide-jsconsole-eval.jpg

    Mozilla's JavaScript engine has built-in support for debugging, and thus can provide powerful tools for JavaScript developers. Venkman, shown in Figure 3, is a powerful, cross-platform JavaScript debugger that integrates with Mozilla. It is usually bundled with Mozilla releases; you can find it at Tools -> Web Development -> JavaScript Debugger. For Firefox, the debugger isn't bundled; instead, you can download and install it from the Venkman Project Page. You can also find tutorials at the development page, located at the Venkman Development Page.

    Mozilla的JavaScript引擎内建了调试功能,这样就提供为JavaScript编写者提供了强有力的工具。图3中的Venkman,与 Mozilla集成,是一个功能强大、跨平台的JavaScript调试工具。它通常包含Mozilla的发行版本中,用户可以点击 Tools -> Web Development -> JavaScript Debugger找到它。对于Firefox,这个调试工具不是集成的;用户可以从Venkman Project Page下载并安装它。用户也会可以在Venkman Development Page找到用户指南。 Figure 3. Mozilla's JavaScript debugger

    Image:migrationguide-venkman.jpg

    The JavaScript debugger can debug JavaScript running in the Mozilla browser window. It supports such standard debugging features as breakpoint management, call stack inspection, and variable/object inspection. All features are accessible through the user interface or through the debugger's interactive console. With the console, you can execute arbitrary JavaScript in the same scope as the JavaScript currently being debugged.

    这个JavaScript调试工具可以调试正在Mozilla浏览器窗口中运行的JavaScript代码。它支持标准的调试功能,像断点管理、查看堆栈、查看变量/对象的值等。所有的调试功能,都可以通过界面或调试工具的命令行被用户使用。在JavaScript代码的调试过程中,只要处于同一个作用域,用户就可以通过命令行运行任意的JavaScript代码。

    [编辑] CSS 的差异

    Mozilla-based products have the strongest support for Cascading Style Sheets (CSS), including most of CSS1, CSS2.1 and parts of CSS3, compared to Internet Explorer as well as all other browsers.

    与IE以及其他浏览器相比,基于Mozilla的产品对层叠样式表(CSS)提供了最好的支持,包括CSS1、CSS2的绝大部分和CSS3的一部分。

    For most issues mentioned below, Mozilla will add an error or warning entry into the JavaScript console. Check the JavaScript console if you encounter CSS-related issues.

    对于下文提到的很多问题,Mozilla会在JavaScript console中显示出error或warning项。如果用户碰到CSS方面的问题,可以去看看JavaScript console。

    [编辑] Mimetypes (when CSS files are not applied)/ mimetype(何时CSS文件不适用)

    The most common CSS-related issue is that CSS definitions inside referenced CSS files are not applied. This is usually due to the server sending the wrong mimetype for the CSS file. The CSS specification states that CSS files should be served with the text/css mimetype. Mozilla will respect this and only load CSS files with that mimetype if the Web page is in strict standards mode. Internet Explorer will always load the CSS file, no matter with which mimetype it is served. Web pages are considered in strict standards mode when they start with a strict doctype. To solve this problem, you can make the server send the right mimetype or remove the doctype. I'll discuss more about doctypes in the next section.

    与CSS相关的问题中,最常见的就是被引用的CSS文件中的CSS定义不适用。这个问题通常是由于服务器给CSS文件发送了错误的 mimetype。CSS的规范中指出,CSS文件的mimetype应该为text/css。如果网页是strict standards mode,Mozilla会遵从这个规范,并且只有在CSS文件的mimetype是text/css时才加载该文件IE不管是那种mimetype,总 会加载CSS文件。网页只有以doctype开头,才被认为是strict standards mode。为了解决这个问题,用户可以让服务器发送正确的mimetype,或者删除doctype。在下面的章节中,我将详细的讲解doctype。

    译注:mime指多用途的网际邮件扩充协议。

    [编辑] CSS and units/ CSS与度量单位

    Many Web applications do not use units with their CSS, especially when you use JavaScript to set the CSS. Mozilla tolerates this, as long as the page is not rendered in strict mode. Since Internet Explorer does not support true XHTML, it does not care if no units are specified. If the page is in strict standards mode, and no units are used, then Mozilla ignores the style:

    很多网页应用程序在它们的CSS中都不使用度量单位,尤其是用户在JavaScript中设置CSS的时候。Mozilla对此很宽容,只要网页不 是在strict mode。因为IE不支持真正的XHTML,即使没有定义度量单位它也不会关心。如果网页是strict standards mode,并且没有使用度量单位,Mozilla将忽略这些样式:

    <DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" 
      "http://www.w3.org/TR/html4/strict.dtd"> 
    <html> 
      <head> 
       <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
       <title>CSS and units example</title> 
      </head> 
      <body> 
        // works in strict mode 
        <div style="width: 40px; border: 1px solid black;">
          Text
        </div>
    
        // will fail in strict mode 
        <div style="width: 40; border: 1px solid black;">
          Text
        </div>
      </body> 
    </html> 
    

    Since the above example has a strict doctype, the page is rendered in strict standards mode. The first div will have a width of 40px, since it uses units, but the second div won't get a width, and thus will default to 100% width. The same would apply if the width were set through JavaScript.

    上面的例子中有明确的doctype定义,所以该网页以 strict standards mode显示。(在显示的结果中)由于第一个div中使用了度量单位,所以它的宽度是40象素;但第二个div没有获取width的值,因此它的 width的值是默认的100%(译注:在firefox2.0中,默认值是40px)。如果width属性是通过JavaScript设置的,同样的事 也会发生。

    分享到: