search
HomeWeb Front-endJS TutorialWeb front-end solutions to browser compatibility issues

This time I will bring you the web front-end solution to the browser compatibility problem. What are the precautions for the web front-end to solve the browser compatibility problem. The following is a practical case. Let’s take a look. .

The so-called browser compatibility problem refers to the situation where different browsers have different parsing of the same piece of code, resulting in inconsistent page display effects. In most cases, our requirement is that no matter what browser the user uses to view our website or log in to our system, there should be a unified display effect. Therefore, browser compatibility issues are issues that front-end developers often encounter and must solve:

1. css3Media queryCompatibility solution: Respond.js

GitHub address: https://github.com/scottjehl/Respond
(from the Internet)
IE8 does not support CSS media queries, which is greatly detrimental to responsive design. Respond.js can help IE6-8 be compatible with "min/max-width" media query conditions.

Usage: Reference Respond.js after the reference location of all css files in the page. And the earlier Respond.js is referenced, the less chance the user will see the page flickering.

2. Custom attribute problem

Problem description: Under IE, you can use the method of obtaining regular attributes to obtain custom attributes, or you can use getAttribute() to obtain custom attributes; under Firefox , custom attributes can only be obtained using getAttribute().
Solution: Uniformly obtain custom attributes through getAttribute().

3. The problem that the variable name is the same as the ID in HTML

Problem description: Under IE, the ID of the HTML object can be used directly as the variable name of the subordinate object of the document, but not under Firefox; Firefox Under IE, you can use the same variable name as the HTML object ID, but not under IE.
Solution: Use document.getElementById("idName") instead of document.idName. It is best not to use variable names with the same HTML object ID to reduce errors; when declaring variables, always add the var keyword to avoid ambiguity.

4. Const problem

Problem description: Under Firefox, you can use the const keyword or the var keyword to define constants; under IE, you can only use the var keyword to define constants.
Solution: Use the var keyword uniformly to define constants. Regarding const, which is a method of defining variables after let in ES6, one thing to note is that
must be assigned a value when declaring a variable, otherwise an error will be reported.

5. Window.event problem

Problem description: window.event can only be run under IE, but not under Firefox. This is because Firefox's event can only be run when the event occurs. For on-site use.
Solution: Add the event parameter to the function where the event occurs, and use var myEvent = evt?evt:(window.event?window.event:null) in the function body (assuming the formal parameter is evt)
Example :

<input type="button" onclick="doSomething(event)"/> 
<script language="javascript"> 
function doSomething(evt) { 
    var myEvent = evt?evt:(window.event?window.event:null) 
    ...} 123456

6. Problems with event.x and event.y

7. Get the position of the mouse on the page
Under IE, the event object has x, y attributes, but not pageX, pageY attributes;
Under Firefox, the event object has pageX, pageY attributes, but no x, y attributes.

Solution:

Use mX (mX = event.x? event.x : event.pageX;) to replace event.x under IE or event.pageX under Firefox.

7. Regarding the frame problem

Take the following frame as an example:
1. Access the frame object
IE: Use window.frameId or window.frameName to access the frame object;
Firefox: Use window.frameName to access the frame object;
Solution: Use window uniformly .document.getElementById("frameId") to access this frame object;
2. Switch frame content
You can use window.document.getElementById("frameId").src = "webjx. com.html" or window.frameName.location = "webjx.com.html" to switch the content of the frame;
If you need to pass the parameters in the frame back to the parent window, you can use the parent keyword in the frame To access the parent window.

8. Body loading problem

Problem description: Firefox's body object exists before the body tag is fully read by the browser; while IE's body object must be before the body tag is read. It does not exist until the browser has completely read it.
[Note] This issue has not been actually verified and will be modified after verification.
[Note] It has been verified that the above problem does not exist in IE6, Opera9 and FireFox2. A simple JS script can access all objects and elements that have been loaded before the script, even if the element has not been loaded yet.

9. Event delegation method

Event对象提供了一个属性叫target,可以返回事件的目标节点,我们成为事件源,也就是说,target就可以表示为当前的事件操作的dom,但是不是真正操作dom,当然,这个是有兼容性的,标准浏览器用ev.target,IE浏览器用event.srcElement,此时只是获取了当前节点的位置,并不知道是什么节点名称,这里我们用nodeName来获取具体是什么标签名,这个返回的是一个大写的,我们需要转成小写再做比较(习惯问题):

window.onload = function(){
     var oUl = document.getElementById("ul1");
     oUl.onclick = function(ev){
        var ev = ev || window.event;
            var target = ev.target || ev.srcElement;
           if(target.nodeName.toLowerCase() == &#39;li&#39;){
                alert(123);
         alert(target.innerHTML);
        }
     }
}1234567891011

十、访问的父元素的区别

问题说明:在IE下,使用 obj.parentElement 或 obj.parentNode 访问obj的父结点;在firefox下,使用 obj.parentNode 访问obj的父结点。 
解决方法:因为firefox与IE都支持DOM,因此统一使用obj.parentNode 来访问obj的父结点。

十一、innerText的问题.

问题说明:innerText在IE中能正常工作,但是innerText在FireFox中却不行。 
解决方法:在非IE浏览器中使用textContent代替innerText。

if(navigator.appName.indexOf("Explorer") >-1){ 
    document.getElementById(&#39;element&#39;).innerText = "my text"; 
} 
else{ 
    document.getElementById(&#39;element&#39;).textContent = ";my text"; 
}123456

十二、用setAttribute设置事件

var obj = document.getElementById(&#39;objId&#39;); 
obj.setAttribute(&#39;onclick&#39;,&#39;funcitonname();&#39;);12

FIREFOX支持,IE不支持 
解决办法: 
IE中必须用点记法来引用所需的事件处理程序,并且要用赋予匿名函数

var obj = document.getElementById(&#39;objId&#39;); 
obj.onclick=function(){fucntionname();};12

十三、设置类名

setAttribute(‘class’,’styleClass’) 
FIREFOX支持,IE不支持(指定属性名为class,IE不会设置元素的class属性,相反只使用setAttribute时IE自动识CLASSNAME属性) 
解决办法如下:

setAttribute(&#39;class&#39;,&#39;styleClass&#39;) 
setAttribute(&#39;className&#39;,&#39;styleClass&#39;) 
//或者直接
 object.className=&#39;styleClass&#39;;123456

十四、绑定事件

在IE下我们通常使用attachEvent方法

var btn1Obj = document.getElementById("btn1"); //object.attachEvent(event,function); btn1Obj.attachEvent("onclick",method1); btn1Obj.attachEvent("onclick",method2); btn1Obj.attachEvent("onclick",method3); 12345

可惜这个微软的私人方法,火狐和其他浏览器都不支持,幸运的是他们都支持W3C标准的addEventListener方法

var btn1Obj = document.getElementById("btn1"); 
//element.addEventListener(type,listener,useCapture); btn1Obj.addEventListener("click",method1,false); 
btn1Obj.addEventListener("click",method2,false); 
btn1Obj.addEventListener("click",method3,false); 12345

顺变说一下这两个的使用方式:

addEventListener的使用方式 

target.addEventListener(type,listener,useCapture);

target: 文档节点、document、window 或 XMLHttpRequest。 
type: 字符串,不含“on”如“click”、“mouseover”、“keydown”等。 
listener :实现了 EventListener 接口或者是 JavaScript 中的函数。 
useCapture :是否使用捕捉,一般用 false 。 
例如:

document.getElementById("testText").addEventListener("keydown", function (event) { alert(event.keyCode); }, false); 1

2.对于attachEvent

target.attachEvent(type, listener);

target: 文档节点、document、window 或 XMLHttpRequest。 
type: 字符串,事件名称,含“on”,比如“onclick”、“onmouseover”、“onkeydown”等。 
listener :实现了 EventListener 接口或者是 JavaScript 中的函数。

例如:

document.getElementById("txt").attachEvent("onclick",function(event){alert(event.keyCode);}); 1

但是他们都给出了事件的移除方法 

removeEventListener(event,function,capture/bubble);

十五、ajax请求

对于ajax请求只要出现兼容性的方面就是创建对象时候的区别我们要考虑IE6的情况,下面给出代码

   //设置IE6的情况,注意,在判断XMLHttpRequest是否存在时将其
    //设置为window.XMLHttpRequest,这样将其设置为属性,在检测时就不是未定义
    //而是undefine
    //1.创建Ajax对象
    if(window.XMLHttpRequest){        var oAjax=new XMLHttpRequest();
    }    else{        var oAjax=new ActiveXObject("Microsoft.XMLHTTP");
    }

相信看了本文案例你已经掌握了方法,更多精彩请关注php中文网其它相关文章!

推荐阅读:

前端页面测试的方法

javascript中call与apply的应用

The above is the detailed content of Web front-end solutions to browser compatibility issues. For more information, please follow other related articles on the PHP Chinese website!

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
JavaScript Comments: A Guide to Using // and /* */JavaScript Comments: A Guide to Using // and /* */May 13, 2025 pm 03:49 PM

JavaScriptusestwotypesofcomments:single-line(//)andmulti-line(//).1)Use//forquicknotesorsingle-lineexplanations.2)Use//forlongerexplanationsorcommentingoutblocksofcode.Commentsshouldexplainthe'why',notthe'what',andbeplacedabovetherelevantcodeforclari

Python vs. JavaScript: A Comparative Analysis for DevelopersPython vs. JavaScript: A Comparative Analysis for DevelopersMay 09, 2025 am 12:22 AM

The main difference between Python and JavaScript is the type system and application scenarios. 1. Python uses dynamic types, suitable for scientific computing and data analysis. 2. JavaScript adopts weak types and is widely used in front-end and full-stack development. The two have their own advantages in asynchronous programming and performance optimization, and should be decided according to project requirements when choosing.

Python vs. JavaScript: Choosing the Right Tool for the JobPython vs. JavaScript: Choosing the Right Tool for the JobMay 08, 2025 am 12:10 AM

Whether to choose Python or JavaScript depends on the project type: 1) Choose Python for data science and automation tasks; 2) Choose JavaScript for front-end and full-stack development. Python is favored for its powerful library in data processing and automation, while JavaScript is indispensable for its advantages in web interaction and full-stack development.

Python and JavaScript: Understanding the Strengths of EachPython and JavaScript: Understanding the Strengths of EachMay 06, 2025 am 12:15 AM

Python and JavaScript each have their own advantages, and the choice depends on project needs and personal preferences. 1. Python is easy to learn, with concise syntax, suitable for data science and back-end development, but has a slow execution speed. 2. JavaScript is everywhere in front-end development and has strong asynchronous programming capabilities. Node.js makes it suitable for full-stack development, but the syntax may be complex and error-prone.

JavaScript's Core: Is It Built on C or C  ?JavaScript's Core: Is It Built on C or C ?May 05, 2025 am 12:07 AM

JavaScriptisnotbuiltonCorC ;it'saninterpretedlanguagethatrunsonenginesoftenwritteninC .1)JavaScriptwasdesignedasalightweight,interpretedlanguageforwebbrowsers.2)EnginesevolvedfromsimpleinterpreterstoJITcompilers,typicallyinC ,improvingperformance.

JavaScript Applications: From Front-End to Back-EndJavaScript Applications: From Front-End to Back-EndMay 04, 2025 am 12:12 AM

JavaScript can be used for front-end and back-end development. The front-end enhances the user experience through DOM operations, and the back-end handles server tasks through Node.js. 1. Front-end example: Change the content of the web page text. 2. Backend example: Create a Node.js server.

Python vs. JavaScript: Which Language Should You Learn?Python vs. JavaScript: Which Language Should You Learn?May 03, 2025 am 12:10 AM

Choosing Python or JavaScript should be based on career development, learning curve and ecosystem: 1) Career development: Python is suitable for data science and back-end development, while JavaScript is suitable for front-end and full-stack development. 2) Learning curve: Python syntax is concise and suitable for beginners; JavaScript syntax is flexible. 3) Ecosystem: Python has rich scientific computing libraries, and JavaScript has a powerful front-end framework.

JavaScript Frameworks: Powering Modern Web DevelopmentJavaScript Frameworks: Powering Modern Web DevelopmentMay 02, 2025 am 12:04 AM

The power of the JavaScript framework lies in simplifying development, improving user experience and application performance. When choosing a framework, consider: 1. Project size and complexity, 2. Team experience, 3. Ecosystem and community support.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools