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:
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:
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:
var year= new Date().getYear(); year = (year<1900?(1900 year):year); document.write(year);
It can also be called through getFullYear getUTCFullYear:
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:
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:
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:
document.getElementById("header").style.styleFloat = "left";
Write this in Firefox:
document.getElementById("header").style.cssFloat = "left";
[Compatibility processing] Add a judgment before writing to determine whether the browser is IE:
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 tag
【Analysis explanation】Same as the "float" attribute, you also need to use invisible syntax distinction to access the "for" in the tag.
Write this in IE:
var myObject = document.getElementById("myLabel"); var myAttribute = myObject.getAttribute("htmlFor");
Write this in Firefox:
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:
var myObject = document.getElementById("header"); var myAttribute = myObject.getAttribute("className");
Applicable to IE8.0 and firefox writing method:
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.
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:
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:
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】
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:
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.
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:
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:
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:
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
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:
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】
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】
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:
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
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
option.text = 'foooooooo';
IE: can only be set
option.innerHTML = 'fooooooo';
Method to delete a selected option:
Firefox: Yes
select.options.remove(selectedIndex);
IE7: It can be used
select.options[i] = null;
IE6: Need to write
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:
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:
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 of this Website
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
Recommended: Excellent JS open source face detection and recognition project
Apr 03, 2024 am 11:55 AM
Face detection and recognition technology is already a relatively mature and widely used technology. Currently, the most widely used Internet application language is JS. Implementing face detection and recognition on the Web front-end has advantages and disadvantages compared to back-end face recognition. Advantages include reducing network interaction and real-time recognition, which greatly shortens user waiting time and improves user experience; disadvantages include: being limited by model size, the accuracy is also limited. How to use js to implement face detection on the web? In order to implement face recognition on the Web, you need to be familiar with related programming languages and technologies, such as JavaScript, HTML, CSS, WebRTC, etc. At the same time, you also need to master relevant computer vision and artificial intelligence technologies. It is worth noting that due to the design of the Web side
How compatible is the Go language on Linux systems?
Mar 22, 2024 am 10:36 AM
The Go language has very good compatibility on Linux systems. It can run seamlessly on various Linux distributions and supports processors of different architectures. This article will introduce the compatibility of Go language on Linux systems and demonstrate its powerful applicability through specific code examples. 1. Install the Go language environment. Installing the Go language environment on a Linux system is very simple. You only need to download the corresponding Go binary package and set the relevant environment variables. Following are the steps to install Go language on Ubuntu system:
What should I do if win11 cannot use ie11 browser? (win11 cannot use IE browser)
Feb 10, 2024 am 10:30 AM
More and more users are starting to upgrade the win11 system. Since each user has different usage habits, many users are still using the ie11 browser. So what should I do if the win11 system cannot use the ie browser? Does windows11 still support ie11? Let’s take a look at the solution. Solution to the problem that win11 cannot use the ie11 browser 1. First, right-click the start menu and select "Command Prompt (Administrator)" to open it. 2. After opening, directly enter "Netshwinsockreset" and press Enter to confirm. 3. After confirmation, enter "netshadvfirewallreset&rdqu
Can I use Bluetooth headphones in airplane mode?
Feb 19, 2024 pm 10:56 PM
With the continuous development of modern technology, wireless Bluetooth headsets have become an indispensable part of people's daily lives. The emergence of wireless headphones frees our hands, allowing us to enjoy music, calls and other entertainment activities more freely. However, when we fly, we are often asked to put our phones in airplane mode. So the question is, can I use Bluetooth headphones in airplane mode? In this article, we will explore this question. First, let’s understand what airplane mode does and means. Airplane mode is a special mode for mobile phones
Detailed explanation of win11 compatibility issues with win10 software
Jan 05, 2024 am 11:18 AM
The software in the win10 system has been perfectly optimized, but for the latest win11 users, everyone must be curious about whether this system can be supported, so the following is a detailed introduction to the win11 software that does not support win10. Come and find out together. Does win11 support win10 software: 1. Win10 system software and even Win7 system applications are well compatible. 2. According to feedback from experts who use the Win11 system, there are currently no application incompatibility issues. 3. So you can upgrade boldly with confidence, but ordinary users are advised to wait until the official version of Win11 is released before upgrading. 4. Win11 not only has good compatibility, but also has Windo
WIN10 compatibility lost, steps to recover it
Mar 27, 2024 am 11:36 AM
1. Right-click the program and find that the [Compatibility] tab is not found in the properties window that opens. 2. On the Win10 desktop, right-click the Start button in the lower left corner of the desktop and select the [Run] menu item in the pop-up menu. 3. The Win10 run window will open, enter gpedit.msc in the window, and then click the OK button. 4. The Local Group Policy Editor window will open. In the window, click the [Computer Configuration/Administrative Templates/Windows Components] menu item. 5. In the opened Windows component menu, find the [Application Compatibility] menu item, and then find the [Remove Program Compatibility Property Page] setting item in the right window. 6. Right-click the setting item, and in the pop-up menu
The relationship between js and vue
Mar 11, 2024 pm 05:21 PM
The relationship between js and vue: 1. JS as the cornerstone of Web development; 2. The rise of Vue.js as a front-end framework; 3. The complementary relationship between JS and Vue; 4. The practical application of JS and Vue.
Best practices for resolving PHP function compatibility issues
May 01, 2024 pm 02:42 PM
Best practices to solve PHP function compatibility issues: Use versioned function names (for example: array_map_recursive()) Leverage function aliases (for example: functionarray_map($callback,$array){...}) to check function availability (for example: if (function_exists('array_map_recursive')){...}) use namespace (for example: namespaceMyNamespace{...})
See all articles