Solutions to common browser compatibility problems at the front end

Posted by Klojum on Tue, 14 Sep 2021 05:51:30 +0200

preface:

Different browsers have different kernels, so there are some differences in web page parsing among browsers.
The browser kernel is mainly divided into two types: rendering engine and js engine
Therefore, browser compatibility generally refers to css compatibility and js compatibility

browserKernel (rendering engine)
Chrome GoogleBefore Webkit, the Blink kernel has been changed
FireFox FirefoxGecko
Safari appleWebkit
IETrident
Opera oppenThe Blink kernel of Google Chrome has been used instead

  1, css compatible

1. The default margin and padding are different for different browsers

Problem symptoms: write a few labels casually. Without style control, their margin and padding are quite different.

Touch frequency: 100%

Solution:

In CSS * {margin:0;padding:0;} but the performance is not good
Generally, we will introduce reset.css style reset;
Note: This is the most common and easy to solve browser compatibility problem. The style will be reset at the beginning of all CSS files. The internal and external patches of each tag are 0.

-moz-  /* Firefox browser  /
-Webkit-  /  Safari, Google browser and other browsers using Webkit engine  /
-o-  /  Opera browser (early)  /
-ms- / IE */

Which css3 attributes need to be added:

Define keyframe animation @keyframes
css3 Deformation in( transform),transition(transtion),animation(animation)
border-radius fillet
box-shadow  Box shadow
flex  Elastic layout
....

  use:

.myClass {
	-webkit-animation-name: fadeIn;
	-moz-animation-name: fadeIn;
	-o-animation-name: fadeIn;
	-ms-animation-name: fadeIn;
	animation-name: fadeIn;  /* No prefixes last */
}
/* Complex attribute keyframes */
@-webkit-keyframes fadeIn {
	0% { opacity: 0; } 100% { opacity: 0; }
}
@-moz-keyframes fadeIn {
	0% { opacity: 0; } 100% { opacity: 0; }
}
@-o-keyframes fadeIn {
	0% { opacity: 0; } 100% { opacity: 0; }
}
@-ms-keyframes fadeIn {
	0% { opacity: 0; } 100% { opacity: 0; }
}
/* No prefixes last */
@keyframes fadeIn {
	0% { opacity: 0; } 100% { opacity: 0; }
}

3. When there is a horizontal margin after the block attribute tag float, the IE browser margin is doubled

Problem symptoms: the common symptom is that the last block in IE6 is pushed to the next line

Solution: for a div set to float, the margin set under ie will double. This is a bug in ie6. The solution is to add display:inline to this div;

<divid="imfloat">
Corresponding css by
# imfloat{
float:left;
margin:5px;//It is understood as 10px under IE
display:inline;//Under IE, it can be understood as 5px}h

remarks:   div+CSS layout is the most commonly used layout, and div is a typical block attribute tag. We usually use div float to implement the horizontal layout. If the horizontal spacing setting is implemented with margin, this is an inevitable compatibility problem.

4. Set a small height label (generally less than 10px). In IE6 and IE7, the height exceeds the set height
Problem symptoms:   Set the div height to be less than 10px. The height of IE6, 7 and the div in the tour exceeds the 10px set by yourself

Encounter frequency:   60%
Solution:

  1. Set overflow:hidden for labels exceeding the height;
  2. Or set the line height to be less than the height you set.

remarks:   This usually occurs in labels with small rounded background. The reason for this problem is that browsers before IE8 will give the label a minimum default row height. Even if your label is empty, the height of the label will reach the default row height.

5. For the in-line attribute tag, after setting display:block, the float layout is adopted, and there is a horizontal margin. IE6 spacing bug

Problem symptom: the spacing ratio in IE6 exceeds the set spacing

Encounter probability: 20%

Solution: add display:inline;display:table after display:block;

Note: for the inline attribute tag, in order to set the width and height, we need to set display:block; (except that the input/img tag is special) After using the float layout and having a horizontal margin, under IE6, it has the bug of the horizontal margin after the block attribute float. However, because it itself is an inline attribute tag, its height and width cannot be set if we add display:inline. At this time, we also need to add display:inline after display:inline

6. The minimum width and height of IE browser div

Problem symptom: IE browser div minimum width and height do not take effect

IE does not recognize the definition of min, but in fact, it takes the normal width and height as the case with min. this is a big problem. If only the width and height are used, the two values in the normal browser will not change. If only the Min width and min height are used, the width and height under IE are not set at all.

For example, to set the background picture, the minimum width is important. To solve this problem, you can:

#box{
  width: 80px;
  height: 35px;
  }
html>body #box{
 width: auto;
 height: auto; 
 min-width: 80px; 
 min-height: 35px;
 }

7. There is no problem with hover style after hyperlink access

The clicked hyperlink style no longer has hover and active. Many people should have encountered this problem. The solution is to change the order of CSS properties:   L-V-H-A

Code:

<style type="text/css">

a:link {}
a:visited {}
a:hover {}
a:active {}

</style>

8. The picture has spacing by default

Problem symptom: when several img tags are placed together, some browsers will have a default spacing, and wildcard clearance spacing does not work.

Encounter probability: 20%

Solution: use the float attribute to layout img (all pictures float to the left)

Note: because img tags are in-line attribute tags, IMG tags will be arranged in one line as long as they do not exceed the width of the container, but there will be a gap between img tags in some browsers. Removing this gap and using float is the right way.

9. css hack solves browser compatibility

Different browsers recognize different styles. csshack itself is compatible with browsers.
The following is how css hack is written:

background-color:yellow0; 0 It's for ie8 of
+background-color:pink;   + ie7 Yes;
_background-color:orange; _For the magical ie6;

2, js compatible

1. Event binding

IE: dom.attachEvent();
Standard browser: dom.addEventListener('click',function(event){},false);

The standard browser adopts the event capture method to correspond to the event bubbling mechanism of IE (i.e. standard from the outermost element to the innermost element or ie from the innermost element to the outermost element) Finally, the standard party also thinks that IE is reasonable in this aspect, so it incorporates event bubbling into the standard, which is also the origin of the third parameter of addEventListener. Moreover, event bubbling is used as the default value, and the third value is false by default, indicating the event bubbling mode.

If the browser does not support the addEventListener() method, you can use the attachEvent() method instead.

The following example demonstrates a cross browser solution:

var x = document.getElementById("myBtn");
if (x.addEventListener) {   //All mainstream browsers, ie9+
    x.addEventListener("click", myFunction);
} else if (x.attachEvent) {      // IE 8 and earlier
    x.attachEvent("onclick", myFunction);
}

2. event object problem

    document.onclick=function(ev){//The writing method of Google Firefox is supported above IE9 and not below;
        var e=ev;
        console.log(e);
    }
    document.onclick=function(){//Google and IE support, Firefox does not support;
        var e=event;
        console.log(e);
    }
    document.onclick=function(ev){//Compatible writing;
        var e=ev||window.event;
        var mouseX=e.clientX;//Coordinates of the X axis of the mouse
        var mouseY=e.clientY;//Coordinates of the Y axis of the mouse
    }

2. Event.srclelement (event source object) problem
IE:   The event object has the srclelement attribute, but does not have the target attribute;
Firefox:   The event object has a target attribute but no srclelement attribute.
resolvent:

srcObj = event.srcElement?event.srcElement:event.target;

3. Get the non line style value of the element:

IE:   dom.currentStyle ['width'] gets the height of the element
Standard browser:   window.getComputedStyle(obj, null)['width'];

Cross browser compatibility solutions:

 // Gets the compatible writing of the element attribute value
  function getStyle(obj,attr){
      if(obj.currentStyle){
         //Compatible with IE
       obj.currentStyle[attr];
          return obj.currentStyle[attr];
      }else{
         //Non IE,
     return window.getComputedStyle(obj, null)[attr]; 
      }
   }

4. Prevent the event from bubbling:

//js prevents event propagation. Here, click event is used as an example
    document.onclick=function(e){
        var e=e||window.event;
        if (e.stopPropagation) {
            e.stopPropagation();//W3C standard
        }else{
            e.cancelBubble=true;//IE....
        }
    }

5. Block event default behavior:

//js block default events generally prevent a link href, form submit from submitting
    document.onclick=function(e){
        var e=e||window.event;
        if (e.preventDefault) {
            e.preventDefault();//W3C standard
        }else{
            e.returnValue='false';//IE..
        }
    }

6. ajax compatibility

IE:  ActiveXObject
other:   xmlHttpReuest

It was not created with XMLHttpRequest before IE6, so we need to be compatible with browsers before IE6 and judge whether it has XMLHttpRequest()

Cross browser compatibility solutions

<script>
	window.onload = function(){
		var oBtn = document.getElementById('btn');
		oBtn.onclick = function(){
			//1. Create ajax objects
			//Only non IE6 browsers are supported
			var oAjax = null;
			if(window.XMLHttpRequest){
				oAjax = new XMLHttpRequest();				
				//alert(new XMLHttpRequest());
			}else{
				//Only IE6 browsers are supported
				oAjax = new ActiveXObject("Microsoft.XMLHTTP");	
			}
			//2. Connect to the server and add a time parameter here. Each access address is different. The browser does not need the buffer in the browser, but
			//	But the server does not parse this time
			oAjax.open("get","a.txt?t=" + new Date().getTime(),true);
			//3. Send
			oAjax.send(null);		
			//4. Receiving information
			oAjax.onreadystatechange = function(){
				//Where is the interaction between the browser and the server? When it is equal to 4, it means that the reading is completed
				if(oAjax.readyState==4){
					//The status code, only equal to 200, indicates that the acceptance is completed and successful
					if(oAjax.status==200){
						alert("success" + oAjax.responseText);	
					}else{
						alert("fail");	
					}	
				}	
			};
				
		};
	};
</script>


Topics: Javascript html5 css