Home  >  Article  >  Web Front-end  >  JavaScript compatibility issues under IE and FF_Basic knowledge

JavaScript compatibility issues under IE and FF_Basic knowledge

WBOY
WBOYOriginal
2016-05-16 16:47:441028browse

JavaScript compatibility has long been a major issue for web developers. Many developers struggle with the differences between formal specifications, de facto standards, and implementations. To this end, we mainly summarize the Javascript compatibility of IE and Firefox from the following aspects:

Copy the code The code is as follows:

1. Differences in functions and methods;
2. Style access and setting;
3. DOM methods and object references;
4. Event processing;
5. Other differences Compatible processing.

1. Differences between functions and methods

1. getYear() method

[Analysis instructions] First look at the following code:

Copy code The code is as follows:

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

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

[Compatibility processing] Add the judgment of the year, such as:

Copy code The code is as follows:

var year= new Date().getYear();
year = (year<1900?(1900 year):year);
document.write(year);

It can also be called through getFullYear getUTCFullYear:

Copy code The code is as follows:

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

2. eval() function

【Analysis explanation】In IE, you can use eval("idName") or getElementById("idName") to get the HTML object with the id of idName; under Firefox, you can only use getElementById("idName") to get the id of HTML object of idName.

[Compatibility processing] Use getElementById("idName") uniformly to obtain the HTML object with the id idName.

3. const statement

【Analysis Note】The const keyword cannot be used in IE. Such as:

Copy code The code is as follows:

const constVar = 32;

This is a syntax error in IE.

[Compatibility processing] Do not use const and use var instead.

4. var

[Analysis instructions] Please see the following code:

Copy code The code is as follows:

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

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

[Compatibility processing] It is normal to add var before echo. This is the purpose of us mentioning var.

5. const problem

【Analysis Note】The const keyword cannot be used in IE. Such as const constVar = 32; This is a syntax error in IE.

【Solution】Do not use const and use var instead.

2. Style access and settings

1. CSS "float" attribute

[Analysis explanation] The most basic syntax for Javascript to access a given CSS value is: object.style.property, but some CSS properties have the same names as reserved words in Javascript, such as "float", "for", "class "Wait, different browsers write it differently.

Write this in IE:

Copy code The code is as follows:

document.getElementById("header").style.styleFloat = "left";

Write this in Firefox:

Copy code The code is as follows:

document.getElementById("header").style.cssFloat = "left";

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

Copy code The code is as follows:

if(document.all){ //
 document.getElementById("header").style.styleFloat = "left";
}
else{ //When not ie undefined
 document.getElementById("header").style.cssFloat = "left";
}

2. Access "for" in the

【Analysis explanation】Same as the "float" attribute, you also need to use invisible syntax distinction to access the "for" in the

Write this in IE:

Copy code The code is as follows:

var myObject = document.getElementById("myLabel");
var myAttribute = myObject.getAttribute("htmlFor");

Write this in Firefox:

Copy code The code is as follows:

var myObject = document.getElementById("myLabel");
var myAttribute = myObject.getAttribute("for");

[Compatibility Processing] The solution is to first determine the browser type.

3. Access and set class attributes

[Analysis explanation] Also because class is a reserved word in Javascript, these two browsers use different JavaScript methods to obtain this attribute.
How to write all IE versions before IE8.0:

Copy code The code is as follows:

var myObject = document.getElementById("header");
var myAttribute = myObject.getAttribute("className");

Applicable to IE8.0 and firefox writing method:

Copy code The code is as follows:

var myObject = document.getElementById("header");
var myAttribute = myObject.getAttribute("class");

In addition, there are the same differences between the two browsers when using setAttribute() to set the Class attribute.

Copy code The code is as follows:

setAttribute("className",value);

This writing method is applicable to all IE versions before IE8.0. Note: IE8.0 also does not support the "className" attribute.

setAttribute("class",value); Applicable to IE8.0 and firefox.

【Compatible processing】

Method one, write both:

Copy code The code is as follows:

var myObject = document.getElementById("header");
myObject.setAttribute("class","classValue");
myObject.setAttribute("className","classValue");
//Set the header class to classValue

Method 2, both IE and FF support object.className, so you can write it like this:

Copy code The code is as follows:

var myObject = document.getElementById("header");
myObject.className="classValue";//Set the header class to classValue

Method three, first determine the browser type, and then use the corresponding writing method according to the browser type.

4. Object width and height assignment problem

[Analysis explanation] Statements similar to obj.style.height = imgObj.height are invalid in FireFox.

[Compatibility processing] Use obj.style.height = imgObj.height ‘px’;

5. Add style

[Analysis explanation] Use the addRules() method to add styles in IE, such as: styleSheet.addRule("p","color:#ccc",styleSheet.length). This method is not compatible with FF, use insetRule in FF () method replacement. Such as styleSheet.insertRule("p{color:#ccc}",styleSheet.length).

【Compatible processing】

Copy code The code is as follows:

if(styleSheet.insertRule){
 // insertRule() method
}else{
 //addRule() method
}

6. Final style

【Analysis Explanation】Sometimes our customized styles will become invalid because there is an overlap of styles, such as a style defined by a class selector and a style defined by a tag selector, in which case the latter becomes invalid. Then you need to use the final style at this time. The final style in IE is written as ele.currentStyle.property name. The standard writing method in DOM is to use the document.defaultView object, such as document.defaultView.getComputedStyle(elel,null). This method is compatible with FF.

[Compatibility processing] First determine the browser (document.all), and then execute the above method.

3. DOM methods and object references

1. getElementById

[Analysis instructions] Let’s first look at a set of codes:

Copy code The code is as follows:

value="click me" ōnclick="alert(id.value)"/>

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

[Compatibility processing] Try to use the W3C DOM writing method. When accessing the object, use document.getElementById("id") to access the object by ID, and an ID must be unique in the page. Also use the tag name To access the object, use document.getElementsByTagName("div")[0]. This method is supported by many browsers.

Copy code The code is as follows:

onclick="alert(document.getElementById('id').value)" />

2. Collection class object access

[Analysis explanation] Under IE, you can use () or [] to obtain collection objects; under Firefox, you can only use [] to obtain collection objects. Such as:

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

//This writing method can access the scrc attribute of the Form object under IE

【Compatibility processing】Change document.forms("formName") to document.forms["formName"]. Use [] uniformly to obtain collection class objects.

3. Reference to frame

[Analysis explanation] 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 tag is written in the htm inside the top-level window, then it can be accessed like this:

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

Firefox: This window object can only be accessed through window.top.frameName.

[Compatibility processing] Use the name of the frame to access the frame object. In addition, it can be used in IE and Firefox

window.document.getElementById("frameId") to access this frame object.

4. parentElement

[Analysis explanation] IE supports using parentElement and parentNode to obtain the parent node. Firefox can only use parentNode.

[Compatibility] Because both firefox and IE support DOM, parentNode is used to access the parent node.

5. table operation

[Analysis explanation] In the table under IE, whether using innerHTML or appendChild to insert has no effect, but other browsers display normally.

[Compatibility processing] The solution is to add to the element of the table, as shown below:

Copy code The code is as follows:

var row = document.createElement("tr");
var cell = document.createElement("td");
var cell_text = document.createTextNode("Insert content");
cell.appendChild(cell_text);
row.appendChild(cell );
document.getElementsByTagName("tbody")[0].appendChild(row);

6. Remove nodes removeNode() and removeChild()

【Analysis explanation】appendNode can be used normally under IE and Firefox, 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). The return value is the deleted node.

removeNode (false) means to only delete the specified node, and then the original child node of this node is promoted to the child node of the original parent node.

removeNode(true) means to delete the specified node and all its subordinate nodes. The deleted node becomes an orphan node and no longer has child nodes and parent nodes.

[Compatibility processing] There is no removeNode method for nodes in Firefox, and can only be replaced by the removeChild method. First, return to the parent node, and then remove the node to be removed from the parent node.

node.parentNode.removeChild(node);

// In order to work normally under IE and Firefox, take the parent node of the previous layer and then remove it.

7. Nodes obtained by childNodes

[Analysis explanation] The meaning of the subscript of childNodes is different in IE and Firefox. Take a look at the following code:

Copy code The code is as follows:


  • 1

  • 2

  • 3

button value="click me!" onclick=
"alert(document.getElementById('main').childNodes.length)">

Running with IE and Firefox respectively, the result of IE is 3, while the result of Firefox is 7. Firefox uses the DOM specification. "#text" represents text (actually meaningless spaces and line breaks, etc.). It will also be parsed into a node in Firefox. In IE, only text with actual meaning will be parsed into "#text". .

【Compatible processing】

Method 1: When obtaining child nodes, you can use node.getElementsByTagName() to avoid this problem. However, getElementsByTagName is obviously not as good as childNodes for complex DOM structure traversal, because childNodes can better handle the DOM hierarchy.

Method 2: In actual application, when Firefox is traversing child nodes, you might as well add:

in the for loop

if(childNode.nodeName=="#text") continue;//Or use nodeType == 1.

This will allow you to skip some text nodes.

Extended reading

"The difference between childNodes in IE and FireFox"

8. Firefox cannot support innerText

[Analysis explanation] 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 fully compatible with IE. If textContent is not used, innerHTML can be used instead if the string does not contain HTML code. You can also use js to write a method to implement it. You can refer to the article "Implementing the innerText attribute for firefox".

[Compatibility processing] Compatible by determining browser type:

Copy code The code is as follows:
if(document.all){
document. getElementById('element').innerText = "my text";
} else{
document.getElementById('element').textContent = "my text";
}

4. Event handling

If event processing is involved when using JavaScript, you need to know the differences in events in different browsers. There are three main JavaScript event models (refer to "Supporting Three Event Models at Once"), they are NN4, IE4 and W3C/Safar.

1. window.event

[Analysis instructions] Let’s look at a piece of code first

Copy code The code is as follows:
function et()
{
alert (event);//IE: [object]
}

The result of running the above code in IE is [object], but it cannot run in Firefox.

Because in IE, event can be used directly as an attribute of the window object, but in Firefox, the W3C model is used, which propagates events by passing parameters, which means that you need to provide Provide an event response interface.

[Compatibility processing] Add event judgment to get the correct event according to different browsers:

Copy code The code is as follows:
function et()
{
evt =evt?evt:(window.event?window.event:null);
//Compatible with IE and Firefox
alert(evt);
}

2. Obtaining keyboard value

[Analysis explanation] IE and Firefox have different methods of obtaining keyboard values. It can be understood that event.which under Firefox is equivalent to event.keyCode under IE. Regarding the differences between each other, please refer to "Compatibility Test of keyCode, which and charCode in Keyboard Events"

【Compatible processing】

Copy code The code is as follows:

function myKeyPress(evt){
//Compatible IE and Firefox obtain the keyBoardEvent object
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 Key
//do something;
}
}

3. Obtaining event sources

[Analysis explanation] When using event delegation, the event source is obtained to determine which element the event comes from. However, under IE, the event object has the srcElement attribute but no target attribute; under Firefox, the even object has target attributes, but there is no srcElement attribute.

【Compatible processing】

Copy code The code is as follows:

ele=function(evt){ //Capture the current event The object of action
evt=evt||window.event;
return
(obj=event.srcElement?event.srcElement:event.target;);
}

4. Event monitoring

【Analysis explanation】In terms of event listening and processing, IE provides two interfaces: attachEvent and detachEvent, while Firefox provides addEventListener and removeEventListener.

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

Copy code The code is as follows:

function addEvent(elem, eventName, handler) {
if (elem.attachEvent) {
elem.attachEvent("on" eventName, function(){
handler.call(elem)});
//The callback function call() is used 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(){
(), let this point to elem
 } else if (elem.removeEventListener) {
 elem.removeEventListener(eventName, handler, false);
 }
}

It is important to note that under Firefox, this in the event handler function points to the monitored element itself, but this is not the case under IE. You can use the callback function call to make the current context point to the monitored element.

5. Mouse position

[Analysis explanation] Under IE, the even object has x, y attributes, but not pageX, pageY attributes; under Firefox, the even object has pageX, pageY attributes, but no x, y attributes.

【Compatibility processing】Use mX (mX = event.x ? event.x : event.pageX;) to replace event.x under IE or event.pageX under Firefox. To make things more complicated, you also need to consider the absolute position

Copy code The 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);
}

5. Compatibility processing of other differences

1. XMLHttpRequest

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

【Compatible processing】

Copy code The 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 explanation] Modal and non-modal windows can be opened through showModalDialog and showModelessDialog in IE, but Firefox does not support it.

【Solution】Directly use window.open(pageURL, name, parameters) to open a new window. If you need to pass parameters, you can use frame or iframe.

3. input.type attribute problem

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

4. Option operation on select element

To set options, IE and Firefox have different writing methods:

Firefox: can be set directly

Copy code The code is as follows:

option.text = 'foooooooo';

IE: can only be set

Copy code The code is as follows:

option.innerHTML = 'fooooooo';

Method to delete a selected option:

Firefox: Yes

Copy code The code is as follows:

select.options.remove(selectedIndex);

IE7: It can be used

Copy code The code is as follows:

select.options[i] = null;

IE6: Need to write

Copy code The code is as follows:

select.options[i].outerHTML = null;

5. Analysis of img object alt and title

[Analysis explanation] The img object has two attributes, alt and title. The difference is that alt: a prompt when the photo does not exist or there is a load error.

title: tip description of the photo. If title is not defined in IE, alt can also be used as the tip of img. However, in Firefox, both are used exactly as defined in the standard

When defining the img object.

【Compatibility Processing】It is best to write all alt and title objects to ensure that they can be used normally in various browsers.

6. img src refresh problem

[Analysis instructions] Let’s take a look at the code first:

Copy code The code is as follows:


Under IE, this code can be used to refresh the image, but not under FireFox. Mainly a caching issue.

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

Copy code The code is as follows:


Summary

There are many differences in Javascript between IE and Firefox. To achieve compatibility, I think it is necessary to organize some common ones into a js library, such as DOM operations, event processing, XMLHttpRequest requests, etc., or You can also choose to use some existing libraries (such as jQuery, YUI, ExtJs, etc.), but I think it is still necessary to understand these differences, which will be helpful for us to participate in compatibility and usability code.

There are always more solutions than problems. No matter how frustrating browser compatibility is, front-end developers can always solve it easily!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Previous article:PHP example sharing implementation to display website running time_javascript skillsNext article:PHP example sharing implementation to display website running time_javascript skills

Related articles

See more