JavaScript compatibility Summary for IE and Firefox

Source: Internet
Author: User

JavaScript compatibility has long been a major problem for Web developers. The difference between formal norms, factual standards, and the existence of various implementations has made many developers suffer day and night. To this end, mainly from the following aspects of the differences in the summary of IE and Firefox JavaScript compatibility:

The difference of function and method;

Second, style access and settings;

Third, Dom method and object reference;

Iv. handling of events;

Five, other differences in the compatibility of processing.

I. Differences in functions and methods

1. GetYear () method

"Analysis Notes" first look at the following code:

var year= new Date (). GetYear ();
document.write (year);

The date you get in IE is "2010", and the date you see in Firefox is "110", mainly because the getYear returned in Firefox is the value of "Current year-1900".

"Compatible Processing"

Plus a judgment on the year, such as:

var year= new Date (). GetYear ();
Year = (year<1900? ( 1900+year): Year);d the Ocument.write (year);

can also be called through getFullYear getUTCFullYear:

var year = new Date (). getFullYear ();
document.write (year);

2. Eval () function

"Analysis Notes" in IE, you can use eval ("Idname") or getElementById ("Idname") to get an HTML object with an ID of Idname; Firefox can only use getElementById ("Idname") To get an HTML object with ID idname.

"Compatible processing" unifies the getElementById ("Idname") to obtain an HTML object with an ID of idname.

3. Const DECLARATION

The "Analysis Notes" cannot use the const keyword in IE. Such as:

Const CONSTVAR = 32;

This is a syntax error in IE.

"Compatible processing" does not use const, instead of Var.

4. var

"Analysis Notes" see the following code:

Echo=function (str) {
document.write (str);
}
Pre>

This function is running normally on IE, but the error is under Firefox.

"Compatible processing" and the addition of Var before Echo is normal, and this is what we refer to as Var.

5. Const ISSUES

The "Analysis Notes" cannot use the const keyword in IE. such as const CONSTVAR = 32; This is a syntax error in IE.

"Workaround" does not use const, instead of Var.

Ii. style access and settings

1. CSS's "float" property

The most basic syntax for JavaScript access to a given CSS value is: Object.style.property, but some CSS properties are named the same as reserved words in JavaScript, such as "float", "for", "class", etc. Different browsers are different in their wording.

In IE, write this:

document.getElementById ("header"). Style.stylefloat = "Left";

In Firefox, write this:

document.getElementById ("header"). Style.cssfloat = "Left";

"Compatible processing" add a judgment before writing to determine if the browser is ie:

if (document.all) {document.getElementById ("header"). Style.stylefloat = "Left";}
else{document.getElementById ("header"). Style.cssfloat = "Left";}

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

As with the "float" attribute, it is also necessary to use the non-existing syntactic distinction to access the "for" in the <label> tag.

In IE, write this:

var myObject = document.getElementById ("MyLabel");
var myattribute = Myobject.getattribute ("htmlfor");

In Firefox, write this:

var myObject = document.getElementById ("MyLabel");
var myattribute = Myobject.getattribute ("for");

The solution for "compatible handling" is to determine the browser type first.

3. Accessing and Setting class properties

"Analysis Notes" also because class is the reason for JavaScript reserved words, both browsers use different JavaScript methods to get this property.

All versions of IE prior to IE8.0:

var myObject = document.getElementById ("header");
var myattribute = Myobject.getattribute ("ClassName");

Applies to the IE8.0 and Firefox wording:

var myObject = document.getElementById ("header");
var myattribute = Myobject.getattribute ("class");

Also, when you use SetAttribute () to set the class attribute, the same differences exist between the two browsers.

SetAttribute ("ClassName", value);

This applies to all versions of IE prior to IE8.0, note that IE8.0 also does not support the "ClassName" attribute.

SetAttribute ("Class", value), applies to IE8.0 and Firefox.

"Compatible Processing"

Method One, both of which are written on:

var myObject = document.getElementById ("header");
Myobject.setattribute ("Class", "Classvalue");
Myobject.setattribute ("ClassName", "Classvalue"); Set the header's class to Classvalue

Method two, IE and FF all support object.classname, so you can write:

var myObject = document.getElementById ("header");
Myobject.classname= "Classvalue";//Set header class to Classvalue

Method Three, first determine the browser type, and then according to the browser type to use the corresponding wording.

4. Object width and Height assignment problem

"Analysis Notes" the statement in Firefox similar to obj.style.height = Imgobj.height is invalid.

"Compatible processing" unified use Obj.style.height = Imgobj.height + ' px ';

Iii. DOM methods and object references

1. getElementById

The analysis note first looks at a set of code:

<!--input Object access 1--
<input id= "id" type= "button"
Value= "Click Me" ōnclick= "alert (id.value)"/>

In Firefox, the button does not respond, in IE, it is possible, because for IE, an HTML element ID can be used directly in the script as a variable name, but not in Firefox.

"Compatible processing" as far as possible the use of the Web DOM, when accessing objects, with document.getElementById ("id") to access the object with ID, and an ID in the page must be unique, also in the tag name to access the object, With document.getElementsByTagName ("div") [0]. This approach is supported by more browsers.

<!--input Object Access 2--
<input id= "id" type= "button" value= "click Me" onclick= "alert (document.getElementById (' id '). value)"/>

2. Collection Class object access

"Analysis instructions" under IE, you can use () or [] to get the collection class object; Firefox can only use [] to get collection class objects. Such as:

document.write (Document.forms ("FormName"). src);//The notation can access the SCRC property of a Form object under IE

"Compatible Processing" Changes document.forms ("FormName") to document.forms["FormName"]. Uniform use [] Gets the collection class object.

3. Frame references

"Analysis Notes" IE can access this frame's window object by ID or name, and Firefox can only access the window object of the frame through name.

For example, if the frame tag is written in the HTM inside the topmost window, then this can be accessed:

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

Firefox: This is the only way to access the Window object window.top.frameName.

Compatible processing uses the name of the frame to access the frame object, and Window.document.getElementById ("Frameid") can be used in both IE and Firefox to access the frame object.

4. parentelement

"Analysis Notes" in IE support using parentelement and parentnode to get the parent node. And Firefox can only use parentnode.

"Compatible processing" because both Firefox and IE support DOM, the parentnode is used uniformly to access the parent node.

5. Table operation

"Analysis note" in the table under IE whether with innerHTML or appendchild insert <tr> no effect, and other browsers are displayed normal.

The workaround for "compatible processing" is to add <tr> to the <tbody> element of the table, as shown here:

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 instructions" Appendnode in IE and Firefox can be used normally, but removenode can only be used under IE.

The function of the RemoveNode method is to delete a node, the syntax is Node.removenode (false), or Node.removenode (true), and the return value is the node that is being deleted.

RemoveNode (False) indicates that only the specified node is deleted, and then the original child node of the 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 orphaned node and no longer has a child node and a parent node.

"Compatible processing" in Firefox, the node has no Removenode method and can only be replaced with the RemoveChild method, returning to the parent node and removing the node to remove from the parent node.

Node.parentNode.removeChild (node); In order to be able to use under IE and Firefox normally, take a layer of parent node, then remove.

7. Node acquired by ChildNodes

"Analysis note" childnodes the meaning of the subscript is different in IE and Firefox, look at the following code:

<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, ie results in 3, while Firefox is 7. Firefox uses the DOM specification, "#text" means that text (actually meaningless spaces and line breaks) in Firefox will also be parsed into a node, in IE only meaningful text will be parsed into "#text".

"Compatible Processing"

Method One, when you get a child node, you can avoid this problem by Node.getelementsbytagname (). But getElementsByTagName is not as good as childnodes for complex DOM traversal, because ChildNodes can better handle the DOM hierarchy.

Method Two, in the actual use, Firefox when traversing the child node, it may be added in the For loop:

if (childnode.nodename== "#text") continue;//or use NodeType = = 1.

This allows you to skip over some text nodes.

Extended Reading

"ChildNodes differences in IE and Firefox"

8. Firefox cannot support innertext

"Analysis note" Firefox does not support innertext, it supports textcontent to implement innertext, but Textcontent does not consider the element display mode as innertext, so it is not fully compatible with IE. If you do not use Textcontent, the string contains no HTML code can also be used innerHTML instead. You can also use JS to write a method to achieve, can refer to the "for Firefox to implement innertext properties" article.

"Compatible processing" is compatible by judging the browser type:

if (document.all) {
document.getElementById (' element '). InnerText = "my text";
} else{
document.getElementById (' element '). Textcontent = "my text";
}

Iv. Handling of events

If you are involved in event processing when using JavaScript, you need to know the difference between the events in different browsers, and the main JavaScript event model is three (refer to "Supporting three event Models at Once") , they are NN4, ie4+ and W3c/safar, respectively.

1. window.event

"Analysis Notes" first look at a piece of code

Function ET ()
{
alert (event);//ie: [Object]
}

The above code in IE run the result is [object], and in Firefox can not run.

Because the event in IE can be used as a property of the Window object, but in Firefox, it uses the model of the Internet, which propagates events by means of a parameter, which means you need to provide an interface for your function to respond to events.

"Compatible handling" adds to the event judgment, depending on the browser to get the correct event:

Function ET ()
{
EVT=EVT?EVT: (Window.event?window.event:null); Compatible with IE and Firefox
alert (EVT);
}

2. Access to keyboard values

"Analysis note" IE and Firefox get keyboard values of different methods, you can understand, Firefox under the Event.which and IE under the event.keycode equivalent. Refer to the compatibility test for KeyCode, which, and charcode in keyboard events for different purposes

"Compatible Processing"

function Mykeypress (evt) {//compatible with IE and Firefox for KeyboardEvent objects
EVT = (evt)? EVT: ((window.event)? Window.event: "")//compatible with IE and Firefox to get key values for KeyboardEvent objects
var key = Evt.keycode?evt.keycode:evt.which; if (Evt.ctrlkey && (key = = | | key = = 10)) {//press CTRL and enter at the same time
Do something;
}
}

3. Getting the event source

"Analysis note" When using the event delegate, through the event source to determine exactly which element the event came from, but, under IE, the event object has the Srcelement property, but no target property; Under Firefox, the even object has the target property, However, there is no srcelement attribute.

"Compatible Processing"

Ele=function (EVT) {//Capture the object that the current event is acting on
evt=evt| | window.event;
return (obj=event.srcelement?event.srcelement:event.target;);
}

4. Event Monitoring

"Analysis note" in the event monitoring processing, IE provides attachevent and detachevent two interfaces, and Firefox provides AddEventListener and RemoveEventListener.

The simplest compatibility process for "compatible processing" is to encapsulate both sets of interfaces:

function addevent (Elem, EventName, handler) {
if (elem.attachevent) {
Elem.attachevent ("on" + EventName, function () {Handler.call (Elem)}); Use the callback function call () here 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 () here to point this to Elem
} else if (Elem.removeeventlistener) {
Elem.removeeventlistener (EventName, Handler, false);
}
}

It is important to note that, under Firefox, this point in the event handler is pointing to the listener element itself, but not under IE, using the callback function call to point the current context to the listening element.

5. Mouse position

"Analysis description" under IE, the even object has an X, Y property, but no Pagex,pagey property; Under Firefox, even objects have pagex,pagey properties, but no X, y properties.

"Compatible Processing" uses mx (mx = event.x event.x:event.pagex;) to replace the event.x under IE or the Event.pagex under Firefox. Complex points also have to consider absolute positions.

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. Compatible handling of other differences

1. XMLHttpRequest

"Analysis note" new ActiveXObject ("Microsoft.XMLHTTP"); only works in IE, Firefox does not support, but supports XMLHttpRequest.

"Compatible Processing"

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 Notes" in IE you can open modal and non-modal windows via ShowModalDialog and showModelessDialog, but Firefox does not support it.

"Workaround" opens a new window directly using window.open (pageurl,name,parameters). If you need to pass parameters, you can use a frame or an IFRAME.

3. Input.type Attribute Issues

The Input.type property is read-only under IE, but can be modified under Firefox

4. Option operation on the SELECT element

Settings Options,ie and Firefox are different:

Firefox: can be set directly

Option.text = ' foooooooo ';

IE: can only be set

option.innerhtml = ' fooooooo ';

To remove the option of a Select method:

Firefox: Yes

Select.options.remove (SelectedIndex);

IE7: Can be used

Select.options[i] = null;

IE6: Need to write

select.options[i].outerhtml = null;

5. img Object ALT and Title parsing

The "Analysis Notes" IMG object has ALT and title two attributes, except that alt: a hint when the photo does not exist or the load is wrong.

Title: The tip of the photo, in IE, if not defined title,alt can also be used as an IMG tip, but in Firefox, the two are completely in accordance with the definition of the standard use

When you define an IMG object.

"Compatible processing" is best to write both the ALT and Title objects, which are guaranteed to work in various browsers.

6. IMG's src Refresh issue

"Analysis Notes" look at the code first:

Under IE, this code can be used to refresh the image, but not in Firefox. The main problem is caching.

"Compatible processing" is resolved by adding a random number to the address:

Summarize

There are a lot of differences between IE and Firefox JavaScript, to be compatible, I think it is necessary to put some common into a JS library, such as DOM operations, event processing, XMLHttpRequest requests, etc., or you can choose to use some of the existing libraries ( such as JQUERY,YUI,EXTJS, etc.), but I think it is necessary to look at these differences, which is helpful for us to participate in compatibility and usability code.

Method is always more than the problem, regardless of browser compatibility how to toss people, do the front-end development can always solve!

This address: http://www.cnblogs.com/wiky/archive/2010/01/09/IE-and-Firefox-Javascript-compatibility.html

JavaScript compatibility Summary for IE and Firefox

Related Article

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.