本文正在翻譯中,原文請參考 Migrate apps from Internet Explorer to Mozillajavascript
當Netscape最初推出Mozilla瀏覽器的時候, 特別考慮對W3C標準的支持. 因此Mozilla並不對Netscape Navigator 4.x 和微軟IE遺留的源碼作向後支持. 例如, Mozilla不支持<layer>
, 我在後面會進行討論. 那些像IE4同樣, 在W3C標準概念以前開發的瀏覽器遺留了不少毛病. 在這篇文章裏, 我將描述Mozilla的"Quirks Mode". 這個模式對IE和其餘遺留下來的瀏覽器提供強大的向後HTML源碼兼容性.css
我還會歸納一些非標準的技術. 好比XMLHttpRequest和富文本編輯那些Mozilla支持, 但到目前爲止尚未W3C標準的(技術). 它們包括:html
儘管網絡標準明確存在, 不一樣瀏覽器表現仍是不一樣 (其實, 同一瀏覽器在不一樣操做系統上也可能不同). 不少瀏覽器, 包括IE, 也支持W3C以前的API, 並從沒普遍地爲W3C兼容的API進行支持.java
在我詳細論述Mozilla和IE的不一樣以前, 我要先講一下一些關於如何令網絡應用程序能夠擴展來對從此新的瀏覽器支持的基本方法.node
由於不一樣瀏覽器有時針對相同的功能, 使用不一樣的API, 你常常能夠在源碼中找到多個用來區分瀏覽器的if() else()
的語句塊. 下面這段源碼是針對IE的 (只有用IE才被解析) :web
. . . 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]; }
首先,我要討論HTML在Mozilla和Internet Explorer中表現的區別。
傳統瀏覽器將工具提示引進HTML中,在連接上顯示它們,並使用alt
屬性的值做爲工具提示的內容。最新的W3C HTML規範創造了title
屬性,意欲包含連接的詳細描述。現代瀏覽器將使用title
屬性來顯示工具提示,且Mozilla只支持爲此屬性顯示工具提示而不支持alt
屬性。
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  
or with its equivalent character reference
.
HTML 置標包含了W3C 網頁標準體定義的幾個標準。你能夠經過引用數字或字符來引用實體。例如,你可使用 
以引用白色空格字符#160;或使用它的等價字符引用
。
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,有這樣的慣例,即容許在常規文本內容末尾替換;
(分號)字符以使用實體:
  Foo    Foo
Mozilla will render the above  
as white spaces, even though that is against the W3C specification. The browser will not parse a  
if it is directly followed by more characters, for example:
Mozilla提供上述 
做爲白色空格,即使這違反了W3C規範。若是 
後直接連着更多的字符,瀏覽器不會解析此代碼,例如:
 12345
This code does not work in Mozilla, since it goes against the W3C web standards. Always use the correct form (
) to avoid browser discrepancies.
這段代碼在Mozilla中無效,由於它違反了W3C標準。請始終使用正確的格式(
) 以免瀏覽器不兼容。
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僅實現了一些成爲最終W3C標準的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.layers
和document.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 DOM1的getElementsByTagName()返回一個具備相同標籤元素的索引,在JavaScript中,它返回一個包含全部元素的數組對像,並可被 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 使用。
程序 | 描述 |
---|---|
document.getElementById( aId ) | 對指定ID的單元返回索引。 |
document.getElementsByTagName( aTagName ) | 對指定文檔中名稱的單元返回數組。 |
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
屬性。
屬性/程序 | 描述 | ||||||||||||||||||||||||||
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
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.返回當前節點的類型。
|
||||||||||||||||||||||||||
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. 返回當前節點的值。對包含文本的節點,例如文本節點和註釋節點,將返回它們的字符串值。對屬性節點則返回屬性值。對其它全部節點返回 |
||||||||||||||||||||||||||
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.write
,document.open
與document.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中不標準、不被支持的內容操控程序,包括取回數值,在節點附近添加文本和單元,例如getAdjacentElement
與insertAdjacentHTML
。表3顯示了W3C標準和Mozilla是如何操控內容的,它們都是任意DOM節點的程序。
程序 | 描述 |
---|---|
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並返回被移除節點的索引。 |
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是變量類型,故不翻譯。
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存在一些差別;經常涉及有關時間消耗的問題。
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仍保持標準的方式。
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
)。
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>
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
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
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
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代碼。
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)提供了最好的支持,包括CSS一、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。
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指多用途的網際郵件擴充協議。
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設置的,一樣的事 也會發生。
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;"> Text </div> <script> var myElm = document.getElementById("myDiv"); myElm.style.width = "40px"; </script>
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轉換成數字。
// 捕獲鼠標移動
mydiv.setCapture();
document.onmousemove = mydivMoveFunc;
// 釋放鼠標移動
mydiv.releaseCapture();
document.onmousemove = null;
對於Firefox瀏覽器來講,要這樣處理:
// 捕獲鼠標移動window.captureEvents(Event.MOUSEMOVE);
window.onmousemove = mydivMoveFunc;
// 釋放鼠標移動
window.releaseEvents(Event.MOUSEMOVE);
window.onmousemove = null;
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;"> a </div> </div>
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.
如圖4所示,Mozilla按照W3C的規範處理。W3C標準說,在這種狀況下,由於內div
(裏面的那個div
)的內容高於外div
,因此內div
會溢出底部。若是用戶喜歡IE的行爲,在外div
中不定義高度就能夠了。
Figure 4. DIV overflow
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的標記把這個區域包圍了起來:
CSS: a:hover {color: green;} HTML: <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. </a>
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:
a:link:hover {color: green;}
, which will only change the color if the element is a link (has an href
attribute). <a />
before the start of the text -- the anchor will continue to work this way. Mozilla徹底聽從CSS的規範,在本例中會把顏色變成綠色。用戶有兩種辦法,可讓Mozilla像IE同樣,在鼠標掠過這段文字時不改變顏色:
a:link:hover {color: green;}
,這樣,只有元素是超連接時(有href
屬性),顏色纔會改變。 <a />
--這樣anchor能夠保留原有的功能。 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.
藍色的部分是公有標識符;綠色的部分是系統標識符,它是個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在下面這些狀況中使用該模式:
text/xml
mimetype or any other XML or XHTML mimetype <!DOCTYPE HTML SYSTEM "http://www.w3.org/TR/REC-html40/strict.dtd">
), except for the IBM doctype 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:
在下面這些狀況下中Mozilla使用準標準模式:
<!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">
) <!DOCTYPE html SYSTEM "http://www.ibm.com/data/dtd/v11/ibmxhtml1-transitional.dtd">
) You can read more about the image gap issue.
讀者能夠閱讀更多關於 圖片間隙的話題。
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.
當前,互聯網上有不少錯誤的HTML標記,也包括只有由於瀏覽器的bug才能起做用的標記。老版本的Netscape瀏覽器——當時市場的主流——是有bug的。當IE成爲市場主流的時候,爲了在當時能處理那些頁面,它模仿了這些bug。當新的瀏覽器面世的時候,原來的大多數bug——一般被稱做quirks——爲了兼容性而被保留了下來。Mozilla在另類顯示模式中支持不少這種頁面。注意,因爲這些「另類」,頁面顯示的速度比它們是標準頁面時要慢。大多數網頁都是以這種模式顯示的。
Mozilla uses quirks mode for the following conditions:
在如下狀況中,Mozilla使用另類模式:
<!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 Behavior和Mozilla'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> <script> function handleEvent(aEvent) { // if aEvent is null, means the Internet Explorer event model, // so get window.event. var myEvent = aEvent ? aEvent : window.event; } </script>
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:
但有時候這不會起做用,由於IE「捕獲」這個aEvent參數,認爲它不是空值,這樣就使得window.event不會被用到。其實簡單的解決辦法是判斷下window.event屬性:
<div onclick="handleEvent(event);">Click me!</div> <script> function handleEvent(aEvent) { var myEvent = window.event ? window.event : aEvent; } </script>
The properties and functions that the event object exposes are also often named differently between Mozilla and Internet Explorer, as Table 4 shows.
Mozilla與IE中,事件屬性和函數的名字一般是不同的,如表4所示:
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:
Mozilla有兩種方法經過JavaScript添加event。第一種,也是全部瀏覽器都支持的,直接給對象(object)添加event屬性。要設置一個click的event句柄,可使用函數的引用設置onclick屬性:
<div id="myDiv">Click me!</div> <script> 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; } </script>
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> <script> 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); } </script>
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規範。
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
:
Mozilla支持經過IFrameElmRef.contentDocument
訪問iframe的document對象的W3C標準;而IE要求用戶經過document.frames["IframeName"]
獲取它,再訪問結果中的document
。
<script> 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; } </script>
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:
下面是Mozillla支持的execCommand命令的列表:
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。
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)
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: <?xml version="1.0"?> <myXMLdoc xmlns:myns="http://myfoo.com"> <myns:foo>bar</myns:foo> </myXMLdoc> JavaScript: var myXMLDoc = getXMLDocument().documentElement; alert(myXMLDoc.childNodes.length);
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: <?xml version="1.0"?> <myXMLdoc xmlns:myns="http://myfoo.com"> <myns:foo>bar</myns:foo> </myXMLdoc> JavaScript: 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) ){ // 不是文本節點或註釋節點 }; };
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"> <foo>bar</foo> </xml> 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"); myDocument.async="false"; myDocument.loadXML(xmlString); }
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); myXMLHTTPRequest.send(null); 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; myXMLHTTPRequest.send(null); }
Table 7 features a list of available methods and properties for Mozilla's XMLHttpRequest
.
表7列出了Mozilla的XMLHttpRequest
全部方法和屬性。
Name | Description | ||||||||||||
---|---|---|---|---|---|---|---|---|---|---|---|---|---|
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 onerror | If set, the references function will be called whenever an error occurs during the request. | ||||||||||||
functionRef onload | If 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 readyState | State of the request. Possible values:
|
||||||||||||
string responseText | String containing the response. | ||||||||||||
DOMDocument responseXML | DOM 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 status | The status code of the HTTP response. |
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."
若是XLST要求用戶區分瀏覽器,用戶能夠查詢系統屬性「xsl:vendor」。Mozilla的XLST引擎會報告說它本身是「transformiix」,而IE將返回「Microsoft」。
<xsl:if test="system-property('xsl:vendor') = 'Transformiix'"> <!-- Mozilla specific markup --> </xsl:if> <xsl:if test="system-property('xsl:vendor') = 'Microsoft'"> <!-- Internet Explorer specific markup --> </xsl:if>
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對象XSLTProcessor
。XSLTProcessor
要求用戶機咱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); myXMLHTTPRequest.send(null); // 獲取XML cocument並加載它 xslStylesheet = myXMLHTTPRequest.responseXML; xsltProcessor.importStylesheet(xslStylesheet); // 加載xmlwenj「example1.xml」 myXMLHTTPRequest = new XMLHttpRequest(); myXMLHTTPRequest.open("GET", "example1.xml", false); myXMLHTTPRequest.send(null); 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文件,而後該文件被傳遞給XSLTProcessor
的transformToDocument
函數。表8列出了XSLTProcessor的函數。
Method | Description |
---|---|
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. |