JavaScript compatibility problem under IE and FF _ basics

Source: Internet
Author: User
Tags eval event listener reserved

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

Copy Code code as follows:

The difference of function and method;
Second, style access and settings;
Three, Dom method and object reference;
Iv. handling of events;
V. Compatibility of other differences.

Differences in functions and methods

1. GetYear () method

"Analysis Notes" first look at the following code:

Copy Code code as follows:

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

In IE, the date is "2010", in Firefox, see the date is "110", mainly because in Firefox inside GetYear return is "Current year-1900" value.

"Compatibility handling" plus a judgment of the year, such as:

Copy Code code as follows:

var year= new Date (). getyear ();
Year = (year<1900? ( 1900+year): Year);
document.write (year);

It can also be invoked via getFullYear getUTCFullYear:

Copy Code code as follows:

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

2. Eval () function

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

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

3. Const statement

The Const keyword cannot be used in IE by the analysis note. Such as:

Copy Code code as follows:

Const CONSTVAR = 32;

This is a syntax error in IE.

"Compatibility handling" does not use const and is substituted with var.

4. var

For an explanation of the analysis, see the following code:

Copy Code code as follows:

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

This function in IE on the normal operation, Firefox under the error.

"Compatible processing" and adding Var before echo is normal, and this is what we refer to as the purpose of Var.

5. The question of the const

The Const keyword cannot be used in IE by the analysis note. such as const CONSTVAR = 32; This is a syntax error in IE.

"Workaround" does not use const and is substituted with var.

Second, style access and settings

1. css "Float" property

The most basic syntax for parsing JavaScript to access 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 written differently.

Write this in IE:

Copy Code code as follows:

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

Write this in Firefox:

Copy Code code as follows:

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

Compatibility processing adds a judgment before writing to determine whether the browser is ie:

Copy Code code as follows:

if (document.all) {//
document.getElementById ("header"). Style.stylefloat = "Left";
}
else{//Non ie for undefined
document.getElementById ("header"). Style.cssfloat = "Left";
}

2. Access <label> tags "for"

As with the "Analysis notes" and "float" properties, it is also necessary to use an ambiguous syntactic distinction to access the "for" in <label> tags.

Write this in IE:

Copy Code code as follows:

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

Write this in Firefox:

Copy Code code as follows:

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

Compatibility handling is also a way to determine the browser type first.

3. Access and Set class properties

The analysis notes also because class is the reason for JavaScript reserved words, the two browsers use different JavaScript methods to get this property.
All versions of IE before IE8.0:

Copy Code code as follows:

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

Apply to IE8.0 and Firefox:

Copy Code code as follows:

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

Also, when you set the class attribute using setattribute (), the same differences exist between the two browsers.

Copy Code code as follows:

SetAttribute ("ClassName", value);

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

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

"Compatibility Handling"

Method One, both of which are written:

Copy Code code as follows:

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 support Object.classname, so you can write this:

Copy Code code as follows:

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

Statements that resemble Obj.style.height = Imgobj.height are not valid in the "Analysis" Firefox.

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

5. Add Style

"Analysis" IE uses the Addrules () method to add styles, such as: Stylesheet.addrule ("P", "Color: #ccc", stylesheet.length). This method is not compatible with FF, which uses insetrule in FF ( ) method substitution. such as Stylesheet.insertrule ("P{color: #ccc}", Stylesheet.length).

"Compatibility Handling"

Copy Code code as follows:

if (stylesheet.insertrule) {
Insertrule () method
}else{
Addrule () method
}

6. Final style

"Analysis Notes" sometimes our custom styles are invalidated because of overlapping styles, such as a style defined by a class selector and a style defined by a label selector, at which point the latter fails. You need to use the final style at this point. The final style in IE is ele.currentstyle. property name. The standard notation in DOM is the use of Document.defaultview objects, such as Document.defaultView.getComputedStyle (Elel,null), which is compatible with FF.

"Compatible processing" first determines the browser (document.all), and then executes the above method.

Iii. DOM methods and object references

1. getElementById

"Analysis Notes" to first look at a set of code:

<!--input Object access 1-->

Copy Code code as follows:

<input id= "id" type= "button"
Value= "Click Me" ōnclick= "alert (id.value)"/>

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

"Compatibility processing" as far as possible using the document.getElementById, access to objects, with the "id" to access the object with ID, and an ID in the page must be unique, also in the name of the tag to access the object, With document.getElementsByTagName ("div") [0]. This way get more browser support.

<!--input Object Access 2-->

Copy Code code as follows:

<input id= "id" type= "button" value= "click Me"
onclick= "Alert (document.getElementById (' id '). value)"/>

2. Collection Class object access

"Analysis of" ie, you can use () or [] Get collection Class objects, Firefox, can only use [] Get collection class objects. Such as:

document.write (Document.forms ("FormName"). Src);

This writing can access the SCRC property of the form object under IE

"Compatibility Handling" changes document.forms ("FormName") to document.forms["FormName"]. Use [] to get collection class objects uniformly.

3. Reference to Frame

"Analytics" IE can access the Window object for this frame by ID or name, and Firefox can only access the Window object for this frame through name.

For example, if the frame tag is written in the HTM in the top-level window, you can access it like this:

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

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

Compatibility handling uses the name of the frame to access the frame object, and in IE and Firefox you can make

Window.document.getElementById ("Frameid") to access this frame object.

4. parentelement

"Analysis" IE supports the use of parentelement and parentnode to obtain parent nodes. And Firefox can only use parentnode.

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

5. Table operation

"Analysis of" ie in the next table either with innerHTML or appendchild insert <tr> has no effect, while other browsers are showing normal.

The workaround for compatibility is to add <tr> to the <tbody> element of the table, as shown in the following:

Copy Code code 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" 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 deleted node.

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 subordinate nodes are deleted. The deleted node becomes an orphaned node and no longer has child nodes and parent nodes.

In the "Compatibility Processing" Firefox, nodes do not have removenode methods, and can only be replaced by the RemoveChild method, which is to go back to the parent node and remove the node to be removed from the parent node.

Node.parentNode.removeChild (node);

In order to be able to use under IE and Firefox, take the parent node of the upper layer and remove it.

7. ChildNodes acquired node

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

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

"Compatibility Handling"

Method One, when you get the child nodes, you can circumvent the problem by Node.getelementsbytagname (). But getelementsbytagname to complex DOM structures is significantly better than using childnodes, because ChildNodes can handle the DOM's hierarchy.

Method Two, in practical use, Firefox in the traversal of child nodes, it may be in the For loop to add:

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

This allows you to skip some text nodes.

Extended Reading

ChildNodes difference in IE and Firefox

8. Firefox can not support the innertext

"Analysis" Firefox does not support innertext, it supports textcontent to achieve innertext, but Textcontent does not consider the element display way like innertext, so it is not completely compatible with IE. If you do not use Textcontent, the string contains no HTML code and can be replaced with innerHTML. You can also use JS to write a method to achieve, you can refer to "for Firefox to achieve innertext properties" a article.

"Compatibility Handling" is compatible by determining browser types:

Copy Code code as follows:

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

Iv. Event Handling

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

1. window.event

"Analysis Notes" read a piece of code first

Copy Code code as follows:

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 as a Window object in IE can be used directly, but in Firefox, the model of the consortium is used, which propagates events by means of parameters, that is, you need to provide an interface of event response for your function.

"Compatibility Handling" adds to the event judgment, depending on the browser to get the correct event:

Copy Code code as follows:

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

2. Access to keyboard values

"Analysis of" IE and Firefox access to keyboard values of different methods, can be understood, Firefox under the Event.which and IE under the event.keycode equivalent. For different purposes, refer to the compatibility test for KeyCode, which, and charcode in keyboard events

"Compatibility Handling"

Copy Code code as follows:

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

3. Access to Event sources

"Analysis Instructions" in the use of event delegates, through the event source to determine the event from which elements, but, in IE, the event object has srcelement properties, but there is no target attribute; Firefox, the even object has the target attribute, However, there is no srcelement attribute.

"Compatibility Handling"

Copy Code code as follows:

Ele=function (EVT) {//Capture the object that the current event acts on
evt=evt| | window.event;
Return
(Obj=event.srcelement?event.srcelement:event.target;);
}

4. Event Monitoring

"Analysis Notes" in the event listener processing, IE provides attachevent and detachevent two interfaces, while Firefox provides AddEventListener and RemoveEventListener.

The simplest compatibility process for "compatibility handling" is to encapsulate these two sets of interfaces:

Copy Code code as follows:

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

In particular, Firefox, the this point in the event handler function points to the listener element itself, and in IE otherwise, the callback function call allows the current context to point to the listening element.

5. Mouse position

"Analysis of" ie, the even object has x,y properties, but there is no Pagex,pagey property, Firefox, even objects have pagex,pagey properties, but no x,y attributes.

"Compatibility Handling" uses mx (mx = event.x Event.x:event.pagex) to replace the event.x under IE or the Event.pagex under Firefox. It's complicated and it's about absolute position.

Copy Code code 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 of other differences

1. XMLHttpRequest

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

"Compatibility Handling"

Copy Code code 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 of" IE can be opened through ShowModalDialog and showModelessDialog modal and modeless windows, but Firefox does not support.

Workaround opens the 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 Property Problem

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

4. Option operation on select element

Set Options,ie and Firefox differently:

Firefox: can be set directly

Copy Code code as follows:

Option.text = ' foooooooo ';

IE: Only Set

Copy Code code as follows:

option.innerhtml = ' fooooooo ';

To delete the option for a select:

Firefox: You can

Copy Code code as follows:

Select.options.remove (SelectedIndex);

IE7: You can use

Copy Code code as follows:

Select.options[i] = null;

IE6: Need to write

Copy Code code as follows:

select.options[i].outerhtml = null;

5. IMG Object ALT and Title analysis

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

Title: 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

When you define an IMG object.

"Compatibility Handling" is best to write all the Alt and title objects, ensuring that they work in all browsers.

6. The src refresh Problem of img

"Analysis Notes" first look at the code:

Copy Code code as follows:


In IE, this code can be used to refresh the picture, but not under Firefox. The main problem is caching.

"Compatibility Handling" is resolved by adding a random number to the following address:

Copy Code code as follows:

Summarize

IE and Firefox JavaScript has a lot of differences, to be compatible, I think it is necessary to put some common into a JS library, such as the operation of the DOM, event processing, XMLHttpRequest request, or you can choose to use some of the existing libraries ( such as Jquery,yui,extjs and so on), but I think it is necessary to understand these differences, so that we participate in compatibility and availability code is very helpful.

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

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.