JavaScript compatibility has long been a major issue for web developers. The differences between formal specifications, factual standards and various implementations have caused many developers to suffer day and night. To this end, the Javascript compatibility of IE and Firefox is mainly summarized from the following differences:
The code copy 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 treatment for other differences.
1. Differences between functions and methods
1. getYear() method
[Analysis Instructions] Let’s take a look at the following code:
The code copy is as follows:
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 in Firefox getYear returns the value of "current year-1900".
【Compatibility Processing】Add to judge the year, such as:
The code copy is as follows:
var year= new Date().getYear();
year = (year<1900?(1900+year):year);
document.write(year);
You can also call it through getFullYear getUTCFullYear:
The code copy is as follows:
var year = new Date().getFullYear();
document.write(year);
2. eval() function
[Analysis Note] In IE, you can use eval("idName") or getElementById("idName") to get HTML objects with idName; in Firefox, you can only use getElementById("idName") to get HTML objects with idName.
[Compatibility Processing] Use getElementById("idName") to obtain HTML object with idName with idName.
3. Const Statement
[Analysis Note] The const keyword cannot be used in IE. like:
The code copy is as follows:
const constVar = 32;
In IE this is a syntax error.
【Compatible Processing】Don't use const, use var instead.
4. var
[Analysis Instructions] Please see the following code:
The code copy is as follows:
echo=function(str){
document.write(str);
}
This function runs normally on IE, but an error was reported under Firefox.
[Compatible Processing] It is normal to add var before echo, and this is the purpose of our mention of var.
5. Const issue
[Analysis Note] The const keyword cannot be used in IE. For example, const constVar = 32; in IE this is a syntax error.
【Solution】Don't use const, use var instead.
2. Style access and settings
1. The "float" attribute of CSS
[Analysis Note] The most basic syntax for Javascript to access a given CSS value is: object.style.property, but some CSS properties are the same as the reserved word names in Javascript, such as "float", "for", "class", etc., and the writing methods are different from different browsers.
In IE, write this:
The code copy is as follows:
document.getElementById("header").style.styleFloat = "left";
In Firefox, write this:
The code copy is as follows:
document.getElementById("header").style.cssFloat = "left";
[Compatibility Processing] Add a judgment before writing to determine whether the browser is IE:
The code copy is as follows:
if(document.all){ //
document.getElementById("header").style.styleFloat = "left";
}
else{ //Undefined when not ie
document.getElementById("header").style.cssFloat = "left";
}
2. Access "for" in the <label> tag
[Analysis Note] Like the "float" attribute, it also requires the use of invisible syntax distinction to access "for" in the <label> tag.
In IE, write this:
The code copy is as follows:
var myObject = document.getElementById("myLabel");
var myAttribute = myObject.getAttribute("htmlFor");
In Firefox, write this:
The code copy 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 properties
[Analysis Note] Also because class is Javascript reserved words, these two browsers use different JavaScript methods to obtain this property.
How to write all IE versions before IE8.0:
The code copy is as follows:
var myObject = document.getElementById("header");
var myAttribute = myObject.getAttribute("className");
Applicable to IE8.0 and firefox writing:
The code copy is as follows:
var myObject = document.getElementById("header");
var myAttribute = myObject.getAttribute("class");
In addition, when setting the Class attribute using setAttribute(), the two browsers also have the same difference.
The code copy is as follows:
setAttribute("className",value);
This writing method is applicable to all IE versions before IE8.0. Note: IE8.0 does not support the "className" attribute.
setAttribute("class",value); is suitable for IE8.0 and firefox.
【Compatible Processing】
Method 1, write both:
The code copy is as follows:
var myObject = document.getElementById("header");
myObject.setAttribute("class","classValue");
myObject.setAttribute("className","classValue");
//Set the header class to classValue
Method 2: IE and FF support object.className, so you can write it like this:
The code copy is as follows:
var myObject = document.getElementById("header");
myObject.className="classValue";//Set the header class to classValue
Method 3: First judge the browser type, and then use the corresponding writing method according to the browser type.
4. Object width and height assignment problem
[Analysis Note] The statement similar to obj.style.height = imgObj.height in FireFox is invalid.
【Compatible processing】Use obj.style.height = imgObj.height + 'px';
5. Add styles
[Analysis Note] In IE, use the addRule() method to add styles, such as: styleSheet.addRule("p","color:#ccc", styleSheet.length). However, this method is not compatible with FF, and use the insetRule() method to replace it in FF. Such as styleSheet.insertRule("p{color:#ccc}",styleSheet.length).
【Compatible Processing】
The code copy is as follows:
if(styleSheet.insertRule){
//insertRule() method
}else{
//addRule() method
}
6. Final style
[Analysis Note] Sometimes our custom styles will fail because style overlap occurs, such as the style defined by a class selector and the style defined by a label selector, and the latter is invalid at this time. Then the final style needs to be used. The final style in IE is written as ele.currentStyle. attribute name. The standard writing method in DOM is to use document.defaultView object, such as document.defaultView.getComputedStyle(elel,null), which is compatible with FF.
[Compatibility Processing] First judge the browser (document.all), and then execute the above method.
3. DOM method and object reference
1. getElementById
[Analysis Instructions] Let’s take a look at a set of codes:
<!-- input object access 1 -->
The code copy is as follows:
<input id="id" type="button"
value="click me" ōnclick="alert(id.value)"/>
In Firefox, the button does not respond, in IE, that's fine, because for IE, the ID of an HTML element can be used directly as a variable name in the script, but not in Firefox.
[Compatibility Processing] Try to use W3C DOM writing. When accessing objects, use document.getElementById("id") to access the object with ID, and an ID must be unique in the page. Also, when accessing objects with a tag name, use document.getElementsByTagName("div")[0]. This method is supported by more browsers.
<!-- input object access 2 -->
The code copy is as follows:
<input id="id" type="button" value="click me"
onclick="alert(document.getElementById('id').value)" />
2. Collection class object access
[Analysis Note] Under IE, you can use () or [] to get the collection class object; under Firefox, you can only use [] to get the collection class object. like:
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 [] to obtain collection class objects in a unified manner.
3. Reference of frame
[Analysis Note] 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 in the uppermost window, you can access it like this:
IE: window.top.frameId or window.top.frameName to access this window object;
Firefox: Only window.top.frameName can be used to access this window object.
【Compatible Processing】Use frame name to access frame objects. In addition, both IE and Firefox can be used to make
window.document.getElementById("frameId") to access this frame object.
4. parentElement
[Analysis Description] IE supports using parentElement and parentNode to obtain parent nodes. Firefox can only use parentNode.
[Compatibility Processing] Because both firefox and IE support DOM, parentNode is used to access the parent node.
5. Table operation
[Analysis Note] In the table under IE, whether it is inserted with innerHTML or appendChild, it has no effect, but other browsers display it normally.
[Compatible Processing] The solution is to add <tr> to the <tbody> element of the table, as shown below:
The code copy 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 Note] appendNode can be used normally in IE and Firefox, but removeNode can only be used in IE.
The function of the removeNode method is to delete a node, with the syntax being node.removeNode(false) or node.removeNode(true), and the return value is the deleted node.
removeNode(false) means that only the specified node is deleted, 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 a child node and a parent node.
[Compatibility Processing] Nodes in Firefox do not have a removeNode method, so they can only be replaced by removeChild method. First return to the parent node and remove the node to be removed from the parent node.
node.parentNode.removeChild(node);
// In order to use both ie and firefox normally, take the parent node of the previous layer and then remove.
7. Nodes obtained by childNodes
[Analysis Note] The meaning of childNodes subscript is different in IE and Firefox. Let’s take a look at the following code:
The code copy 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)">
Running with IE and Firefox respectively, the result of IE is 3, while Firefox is 7. Firefox uses the DOM specification, and "#text" means text (actually meaningless spaces and line breaks, etc.) will also be parsed into a node in Firefox. In IE, only text with practical meaning will be parsed into "#text".
【Compatible Processing】
Method 1: When obtaining child nodes, you can avoid this problem by node.getElementsByTagName(). However, getElementsByTagName is obviously not as good as using childNodes for traversing complex DOM structures, because childNodes can better handle the DOM hierarchy.
Method 2. In actual use, when Firefox traversing child nodes, you might as well add it to the for loop:
if(childNode.nodeName=="#text") continue;//or use nodeType == 1.
This allows you to skip some text nodes.
Further reading
"Difference between childNodes 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 elements like innerText, so it is not completely compatible with IE. If you do not use textContent, the string does not contain HTML code, which can also be replaced by innerHTML. You can also write a method to implement it, please refer to the article "Implementing innerText attribute for firefox".
【Compare Processing】Compare by judging the browser type:
The code copy 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 between events in different browsers. There are three main JavaScript event models (see "Supporting Three Event Models at Once", which are NN4, IE4+ and W3C/Safar.
1. window.event
【Analysis Instructions】Look at a piece of code first
The code copy is as follows:
function et()
{
alert(event);//IE: [object]
}
The result of the above code running in IE is [object], but it cannot be run in Firefox.
Because event can be used directly as a property of a window object in IE, but in Firefox, the W3C model is used, which propagates events through the method of passing parameters, that is, you need to provide an event response interface for your function.
[Compatibility Processing] Add the judgment of event and get the correct event according to the browser:
The code copy is as follows:
function et()
{
evt=evt?evt:(window.event?window.event:null);
//Compatible with IE and Firefox
alert(evt);
}
2. Acquisition of keyboard value
[Analysis Note] The methods of obtaining keyboard values from IE and Firefox are different. It can be understood that the event.which under Firefox is equivalent to the event.keyCode under IE. For each other's differences, please refer to "Compatibility Test for KeyCode, which and charCode in Keyboard Events"
【Compatible Processing】
The code copy is as follows:
function myKeyPress(evt){
//Compatible with IE and Firefox to obtain 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)){
//Ctrl and Enter were pressed at the same time
//do something;
}
}
3. Obtaining event source
[Analysis Note] When using event delegates, we can determine which element the event comes from through event source acquisition. However, in IE, the event object has a srcElement property, but no target property; in Firefox, the even object has a target property, but no srcElement property.
【Compatible Processing】
The code copy is as follows:
ele=function(evt){ //Capture the object that the current event is acting
evt=evt||window.event;
Return
(obj=event.srcElement?event.srcElement:event.target;);
}
4. Event monitoring
[Analysis Note] 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:
The code copy is as follows:
function addEvent(elem, eventName, handler) {
if (elem.attachEvent) {
elem.attachEvent("on" + eventName, function(){
handler.call(elem)});
// Use the callback function call() 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)});
// Use the callback function call() here, let this point to elem
} else if (elem.removeEventListener) {
elem.removeEventListener(eventName, handler, false);
}
}
It should be noted that under Firefox, this in the event handling function points to the listened element itself, but in IE, you can use the callback function call to let the current context point to the listened element.
5. Mouse position
[Analysis Note] Under IE, the even object has x and y attributes, but no pageX and pageY attributes; under Firefox, the even object has pageX and pageY attributes, but no x and y attributes.
[Compatibility Processing] Use mX(mX = event.x ? event.x : event.pageX;) to replace event.x under IE or event.pageX under Firefox. The absolute position must be considered in complex points
The code copy 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 treatment of other differences
1. XMLHttpRequest
[Analysis Note] new ActiveXObject("Microsoft.XMLHTTP"); only works in IE. Firefox does not support it, but supports XMLHttpRequest.
【Compatible Processing】
The code copy 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 Note] In IE, modal and non-modal windows can be opened through showModalDialog and showModelessDialog, but Firefox does not support them.
[Solution] 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 property under IE is read-only, but it can be modified under Firefox.
4. Option operation on select element
Set options, IE and Firefox are written differently:
Firefox: Can be set directly
The code copy is as follows:
option.text = 'fooooooooo';
IE: Only set
The code copy is as follows:
option.innerHTML = 'fooooooo';
Method to delete a select option:
Firefox: Yes
The code copy is as follows:
select.options.remove(selectedIndex);
IE7: Can be used
The code copy is as follows:
select.options[i] = null;
IE6: Need to write
The code copy is as follows:
select.options[i].outerHTML = null;
5. Analysis of img objects alt and title
[Analysis Note] The img object has two attributes: alt and title. The difference is that alt: a prompt when the photo does not exist or the load is incorrect.
title: the tip description of the photo. If the title is not defined in IE, alt can also be used as the tip of img, but in Firefox, both are used exactly according to the definition in the standard.
When defining an img object.
[Compatible processing] It is best to write all alt and title objects to ensure that they can be used normally in various browsers.
6. Img's src refresh problem
[Analysis Instructions] Let’s take a look at the code first:
The code copy is as follows:
<img id="pic" onclick= "this.src= 'a.jpg'" src="aa.jpg" style="cursor: pointer"/>
Under IE, this code can be used to refresh images, but not under FireFox. It's mainly a caching problem.
[Compatibility Processing] Adding a random number after the address will solve it:
The code copy is as follows:
<img id="pic" onclick= "javascript:this.src=this.src+'?'+Math.random()"src="a.jpg" style="cursor: pointer"/>
Summarize
There are many differences in Javascript between IE and Firefox. To be compatible, 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.). However, I think it is still necessary to understand these differences, which is very helpful for us to participate in compatibility and usability code.
There are always more solutions than problems. No matter how the browser is compatible, front-end development can always be solved!