Compatibility of JavaScript in IE and FF

Source: Internet
Author: User

JavaScript compatibility has long been a major problem for Web developers. Many developers suffer day and night due to the differences between formal specifications, fact standards, and various implementations. To this end, we mainly summarize the differences between IE and Firefox in the following aspects:
Copy codeThe Code is as follows:
1. Differences between functions and methods;
2. Style access and settings;
3. DOM method and object reference;
4. event handling;
5. compatibility with other differences.

I. Differences between functions and methods

1. getYear () method

[Analysis description] let's take a look at the following code:

Copy codeThe Code is as follows:
Var year = new Date (). getYear ();
Document. write (year );

The date obtained in IE is "2010", and the date displayed in Firefox is "110", mainly because in Firefox, getYear returns the value of "current year-1900.

[Compatible processing] adds a judgment on the year, such:

Copy codeThe Code is as follows:
Var year = new Date (). getYear ();
Year = (year <1900? (1900 + year): year );
Document. write (year );

You can also use getFullYear getUTCFullYear to call:

Copy codeThe Code is as follows:
Var year = new Date (). getFullYear ();
Document. write (year );

2. eval () function

[Analysis description] in IE, you can use eval ("idName") or getElementById ("idName") to obtain the HTML object whose id is idName; in Firefox, only getElementById ("idName") can be used to obtain the HTML object whose id is idName.

Compatible processing: getElementById ("idName") is used to obtain the HTML object with id as idName.

3. const statement

[Analysis description] the const keyword cannot be used in IE. For example:

Copy codeThe Code is as follows:
Const constVar = 32;

In IE, This Is A syntax error.

[Compatible processing] const is not used, instead of var.

4. var

[Analysis description] See the following code:

Copy codeThe Code is as follows:
Echo = function (str ){
Document. write (str );
}

This function runs normally on IE, but an error is reported in Firefox.

[Compatible processing] it is normal to add var before echo. This is the purpose of var.

5. const Problems

[Analysis description] the const keyword cannot be used in IE. For example, const constVar = 32; in IE, This Is A syntax error.

[Solution] use var instead of const.

Ii. Style access and settings

1. "float" attribute of CSS

[Analysis description] The most basic syntax for Javascript to access a given CSS value is: object. style. property, but some CSS attributes have the same names as the Reserved Words in Javascript, such as "float", "for", and "class". Different browsers write differently.

Write in IE as follows:

Copy codeThe Code is as follows:
Document. getElementById ("header"). style. styleFloat = "left ";

Write in Firefox as follows:

Copy codeThe Code is as follows:
Document. getElementById ("header" ).style.css Float = "left ";

[Compatible processing] Add a judgment before writing to determine whether the browser is IE:

Copy codeThe Code is as follows:
If (document. all ){//
Document. getElementById ("header"). style. styleFloat = "left ";
}
Else {// undefined for non-ie
Document. getElementById ("header" ).style.css Float = "left ";
}

2. Access "for" in the <label> label"

[Analysis description] similar to the "float" attribute, you also need to access "for" in the <label> label using non-existent syntax differentiation ".

Write in IE as follows:

Copy codeThe Code is as follows:
Var myObject = document. getElementById ("myLabel ");
Var myAttribute = myObject. getAttribute ("htmlFor ");

Write in Firefox as follows:

Copy codeThe Code is as follows:
Var myObject = document. getElementById ("myLabel ");
Var myAttribute = myObject. getAttribute ("");

[Compatible processing] the solution is to determine the browser type first.

3. Access and set class attributes

[Analysis description] Because the class is reserved for Javascript, the two browsers use different JavaScript methods to obtain this attribute.
For all IE versions earlier than IE8.0:

Copy codeThe Code is as follows:
Var myObject = document. getElementById ("header ");
Var myAttribute = myObject. getAttribute ("className ");

For IE8.0 and firefox:

Copy codeThe Code is as follows:
Var myObject = document. getElementById ("header ");
Var myAttribute = myObject. getAttribute ("class ");

In addition, when setAttribute () is used to set the Class attribute, the two browsers also have the same difference.

Copy codeThe Code is as follows:
SetAttribute ("className", value );

This method applies to all IE versions earlier than IE8.0. Note: IE8.0 does not support the "className" attribute.

SetAttribute ("class", value); applicable to IE8.0 and firefox.

[Compatible processing]

Method 1 and both are written as follows:

Copy codeThe Code is as follows:
Var myObject = document. getElementById ("header ");
MyObject. setAttribute ("class", "classValue ");
MyObject. setAttribute ("className", "classValue ");
// Set the class of the header to classValue

Method 2: Both IE and FF support object. className, so you can write as follows:

Copy codeThe Code is as follows:
Var myObject = document. getElementById ("header ");
MyObject. className = "classValue"; // set the class of the header to classValue

Method 3: first determine the browser type, and then use the corresponding method based on the browser type.

4. Assignment of object width and height

[Analysis description] The statement similar to obj. style. height = imgObj. height in FireFox is invalid.

[Compatible processing] Use obj. style. height = imgObj. height + 'px ';

5. Add a style

[Analysis description] use the addRules () method in IE to add styleSheet. addRule ("p", "color: # ccc", styleSheet. length ). this method is not compatible with FF and is replaced by the insetRule () method in FF. For example, styleSheet. insertRule ("p {color: # ccc}", styleSheet. length ).

[Compatible processing]

Copy codeThe Code is as follows:
If (styleSheet. insertRule ){
// InsertRule () method
} Else {
// AddRule () method
}

6. Final Style

[Analysis description] Sometimes our custom styles are invalid because of overlapping styles, such as styles defined by a class selector and styles defined by a label selector, the latter is invalid. The final style is required. In IE, the final style is written as ele. currentStyle. attribute name. The standard method in DOM is to use the document. defaultView object, such as document. defaultView. getComputedStyle (elel, null). This method is compatible with FF.

[Compatible processing] first judge the browser (document. all) and then execute the above method.

3. DOM method and Object Reference

1. getElementById

[Analysis description] First, let's look at a group of code:

<! -- Input Object Access 1 -->

Copy codeThe Code is as follows:
<Input id = "id" type = "button"
Value = "click me" Export nclick = "alert (id. value)"/>

In Firefox, buttons do not respond. in IE, you can, because for IE, the ID of an HTML element can be directly used as a variable name in the script, firefox cannot.

[Compatible processing] Use W3C DOM as much as possible. When accessing an object, use document. getElementById ("id") is used to access the object, and an ID must be unique in the page. Similarly, when using the tag name to access the object, use document. getElementsByTagName ("div") [0]. This method is supported by many browsers.

<! -- Input Object Access 2 -->

Copy codeThe Code is as follows:
<Input id = "id" type = "button" value = "click me"
Onclick = "alert (document. getElementById ('id'). value)"/>

2. Access to collection objects

[Analysis description] in IE, you can use () or [] to obtain collection class objects. In Firefox, you can only use [] to obtain collection class objects. For example:

Document. write (document. forms ("formName"). src );

// This method can access the scrc attribute of the Form object in IE.

[Compatible processing] Change document. forms ("formName") to document. forms ["formName"]. Use [] to obtain collection class objects.

3. frame reference

[Analysis description] IE can access the window object corresponding to this frame through id or name, while Firefox can only access the window object corresponding to this frame through name.

For example, if the above frame label is written in the htm in the top window, you can access it as follows:

IE: window. top. frameId or window. top. frameName to access this window object;

Firefox: only window. top. frameName can access this window object.

[Compatible processing] uses the frame name to access the frame object. In addition, both IE and Firefox can enable

Upload metadata Doc ument. getElementById ("frameId") to access this frame object.

4. parentElement

[Analysis description] in IE, parentElement and parentNode can be used to obtain the parent node. Firefox can only use parentNode.

[Compatible processing] because both firefox and IE support DOM, parentNode is used to access the parent node.

5. table operations

[Analysis description] Insert <tr> with innerHTML or appendChild in table in IE does not work, but other browsers do.

[Compatible processing] the solution is to add <tr> to the <tbody> element of the table, as shown below:

Copy codeThe Code is as follows:
Var row = document. createElement ("tr ");
Var cell = document. createElement ("td ");
Var cell_text = document. createTextNode ("inserted content ");
Cell. appendChild (cell_text );
Row. appendChild (cell );
Document. getElementsByTagName ("tbody") [0]. appendChild (row );

6. Remove nodes removeNode () and removeChild ()

[Analysis description] appendNode can be used normally in IE and Firefox, but removeNode can only be used in IE.

The removeNode method is used to delete a node. The syntax is node. removeNode (false) or node. removeNode (true). The return value is the deleted node.

RemoveNode (false) indicates that only the specified node is deleted, and the original child node of this node is promoted to the child node of the original parent node.

RemoveNode (true) indicates that the specified node and all its subordinate nodes are deleted. The deleted node becomes an isolated node and does not have any child node or parent node.

[Compatible processing] nodes in Firefox do not have the removeNode method. They can only be replaced by the removeChild method. First, return to the parent node and remove the node to be removed from the parent node.

Node. parentNode. removeChild (node );

// To ensure normal use of ie and firefox, take the parent node of the previous layer and remove it.

7. nodes obtained by childNodes

[Analysis description] childNodes has different meanings in IE and Firefox. Let's look at the following code:

Copy codeThe Code is as follows:
<Ul id = "main">
<Li> 1 </li>
<Li> 2 </li>
<Li> 3 </li>
</Ul>
<Input type = button value = "click me! "Onclick =
"Alert (document. getElementById ('main'). childNodes. length)">

Run with IE and Firefox respectively. The result of IE is 3, while that of Firefox is 7. Firefox uses the DOM specification. "# text" indicates text (actually meaningless spaces and line breaks). It will also be parsed into a node in Firefox, in IE, only meaningful texts are parsed into "# text ".

[Compatible processing]

Method 1: When obtaining a subnode, you can use node. getElementsByTagName () to avoid this problem. However, getElementsByTagName is obviously inferior to childNodes for complex DOM structure traversal, because childNodes can better process DOM hierarchies.

Method 2: in practice, when Firefox traverses sub-nodes, add the following in the for Loop:

If (childNode. nodeName = "# text") continue; // or use nodeType = 1.

In this way, you can skip some text nodes.

Additional reading

Differences between childNodes in IE and FireFox

8. Firefox cannot support innerText

[Analysis description] Firefox does not support innerText. It supports textContent to implement innerText. However, textContent does not consider the display method of elements like innerText, so it is not completely compatible with IE. If textContent is not required, the string can be replaced by innerHTML without HTML code. You can also use js to write a method for implementation. Refer to the article "Implementing innerText attributes for firefox.

[Compatibility processing] compatibility by determining the browser type:

Copy codeThe Code is as follows:
If (document. all ){
Document. getElementById ('element'). innerText = "my text ";
} Else {
Document. getElementById ('element'). textContent = "my text ";
}

Iv. event handling

If event processing is involved when javascript is used, you need to know the differences between events in different browsers, there are Three main JavaScript Event Models (see Supporting Three Event Models at Once): NN4, IE4 +, and W3C/Safar.

1. window. event

[Analysis description] First read a piece of code.

Copy codeThe Code is as follows:
Function et ()
{
Alert (event); // IE: [object]
}

The above code runs in IE and the result is [object], but cannot run in Firefox.

In IE, the event can be directly used as an attribute of the window object, but the W3C model is used in Firefox. It transmits events by passing parameters, that is to say, You need to provide an Event Response interface for your function.

[Compatible processing] adds an event judgment to get the correct event based on the browser:

Copy codeThe Code is as follows:
Function et ()
{
Evt = evt? Evt :( window. event? Window. event: null );
// Compatible with IE and Firefox
Alert (evt );
}

2. Obtain the keyboard Value

[Analysis description] IE and Firefox use different methods to obtain the keyboard value. You can understand that the event. which in Firefox is equivalent to the event. keyCode in IE. For details about the differences, refer to the keyCode, which, and charCode compatibility test in Keyboard Events.

[Compatible processing]

Copy codeThe Code is as follows:
Function myKeyPress (evt ){
// Compatible with IE and Firefox to obtain keyBoardEvent objects
Evt = (evt )? Evt: (window. event )? Window. event :"")
// Compatible with IE and Firefox to obtain the key value of the keyBoardEvent object
Var key = evt. keyCode? Evt. keyCode: evt. which;
If (evt. ctrlKey & (key = 13 | key = 10 )){
// Press Ctrl and enter at the same time
// Do something;
}
}

3. Event source acquisition

[Analysis description] when using event delegation, you can obtain the event source to determine which element the event comes from. However, in IE, the event object has the srcElement attribute, but does not have the target attribute; in Firefox, the even object has the target attribute, but does not have the srcElement attribute.

[Compatible processing]

Copy codeThe Code is as follows:
Ele = function (evt) {// capture the object to which the current event acts
Evt = evt | window. event;
Return
(Obj = event. srcElement? Event. srcElement: event.tar get ;);
}

4. event listening

[Analysis description] In terms of event listening processing, IE provides attachEvent and detachEvent interfaces, while Firefox provides addEventListener and removeEventListener.

[Compatible processing] The simplest compatibility processing is to encapsulate these two sets of interfaces:

Copy codeThe Code is as follows:
Function addEvent (elem, eventName, handler ){
If (elem. attachEvent ){
Elem. attachEvent ("on" + eventName, function (){
Handler. call (elem )});
// Use the callback function call () to point this to elem.
} Else if (elem. addEventListener ){
Elem. addEventListener (eventName, handler, false );
}
}
Function removeEvent (elem, eventName, handler ){
If (elem. detachEvent ){
Elem. detachEvent ("on" + eventName, function (){
Handler. call (elem )});
// Use the callback function call () to point this to elem.
} Else if (elem. removeEventListener ){
Elem. removeEventListener (eventName, handler, false );
}
}

Note that in Firefox, this in the event processing function points to the listened element itself. In IE, this is not the case. You can use the callback function call to point the current context to the listened element.

5. Mouse position

[Analysis description] in IE, the even object has the x and y attributes, but does not have the pageX and pageY attributes. In Firefox, the even object has the pageX and pageY attributes, but does not have the x and y attributes.

[Compatible processing] Use mX (mX = event. x? Event. x: event. pageX;) to replace event. x in IE or event. pageX in Firefox. Absolute location must be considered for complex points.

Copy codeThe Code is as follows:
Function getAbsPoint (e ){
Var x = e. offsetLeft, y = e. offsetTop;
While (e = e. offsetParent ){
X + = e. offsetLeft;
Y + = e. offsetTop;
}
Alert ("x:" + x + "," + "y:" + y );
}

V. compatibility with other differences

1. XMLHttpRequest

[Analysis description] new ActiveXObject ("Microsoft. XMLHTTP"); only works in IE. Firefox does not support but XMLHttpRequest.

[Compatible processing]

Copy codeThe Code is as follows:
Function createXHR (){
Var xhr = null;
If (window. XMLHttpRequest ){
Xhr = new ActiveXObject ("Msxml2.XMLHTTP ");
} Else {
Try {
Xhr = new ActiveXObject ("Microsoft. XMLHTTP ");
}
Catch (){
Xhr = null;
}
}
If (! Xhr) return;
Return xhr;
}

2. Modal and non-modal windows

[Analysis description] in IE, modal and non-modal windows can be opened through showModalDialog and showModelessDialog, but Firefox does not.

[Solution] Use window. open (pageURL, name, parameters) to open a new window. If you want to pass parameters, you can use frame or iframe.

3. Question about the input. type attribute

The input. type attribute in IE is read-only, but can be modified in Firefox.

4. option operation on the select Element

Set options. IE and Firefox are written differently:

Firefox: can be directly set

Copy codeThe Code is as follows:
Option. text = 'foooooooo ';

IE: can only be set

Copy codeThe Code is as follows:
Option. innerHTML = 'fooooooo ';

To delete a select option:

Firefox: Yes

Copy codeThe Code is as follows:
Select. options. remove (selectedIndex );

IE7: available

Copy codeThe Code is as follows:
Select. options [I] = null;

IE6: Write required

Copy codeThe Code is as follows:
Select. options [I]. outerHTML = null;

5. Analysis of alt and title of img objects

[Analysis description] img objects have the alt and title attributes. The difference is that alt indicates the prompt when the photo does not exist or the load error occurs.

Title: tip description of the photo. If title is not defined in IE, alt can also be used as the img tip. However, in Firefox, the two are completely used according to the standard definition.

When defining an img object.

[Compatible processing] it is best to write all alt and title objects to ensure normal use in various browsers.

6. img src refresh

[Analysis description] first look at the Code:

Copy codeThe Code is as follows:

In IE, this code can be used to refresh the image, but not in FireFox. It is mainly about caching.

[Compatible processing] Add a random number after the address to solve the problem:

Copy codeThe Code is as follows:

Summary

There are many differences between IE and Firefox Javascript. To be compatible, I think it is necessary to organize some common Javascript libraries, such as DOM operations and event processing, XMLHttpRequest requests, or you can choose to use existing libraries (such as jQuery, YUI, ExtJs). However, I think it is necessary to understand these differences, this is helpful for us to participate in compatibility and Availability code.

There are always more problems. No matter how compatible the browser is, front-end development can always be done!

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.