Small knowledge, big challenge! This article is participating in the creation activity of “Essential Tips for Programmers”.

preface

In addition to products, operating system compatibility is one of the biggest headaches for us front-end developers during development. There is no one who does not accept refutation. If you have a tough problem, it looks something like this

So how do we better solve the compatibility problem, solve the headache, but also play a fish. This makes us well informed.

  1. PC browser compatible
  2. Compatible with mobile browser

PC browser compatible

Different browsers have different kernels, so there are some differences in how web pages are parsed. The browser kernel is mainly divided into two kinds, one is the rendering engine, the other is the JS engine, the kernel is more inclined to say the rendering engine. Common browser kernel: \

CSS article

1. Labels of different browsers have different external and internal patches by default

Symptom: The margin and padding of several labels are different without style control.

Frequency of contact :100%

*{margin:0; padding:0; }

Note: This is one of the most common and easiest browser compatibility issues to solve. Almost all CSS files start with the wildcard * to set the internal and external patches of each label to 0.

2. In IE6, the margin is larger than the set margin after the block property tag float

Symptom: A common symptom is that the last block in IE6 is pushed to the next line

Frequency of encounters: 90% (slightly more complex pages, most common browser compatibility issues with float layouts)

Solution: Add display:inline; Convert it to an inline property

Note: The most commonly used layout is div+CSS, and div is a typical block attribute tag. Horizontal layout is usually implemented with div float, and horizontal spacing is implemented with margin, which is an inevitable compatibility problem.

3. Event. X and Event

Symptom: In IE, the Event object has x and Y attributes, but does not have pageX and pageY attributes. In Firefox,event objects have pageX and pageY properties, but no x and y properties.

Frequency of encounter: 50%

Solution: use mX(mX = event.x? event.x : event.pageX;) To replace event. X in IE or Event. PageX in Firefox.

Note: We sometimes implement the ability to drag and drop elements or elements to follow, both of which require the x and Y attributes of the event attribute and the pageX and pageY attributes of the element. This problem is inevitable when you use different browsers.

4. Set a small height TAB (usually less than 10px). When surfing in IE6, IE7, the height is higher than the set height

Symptom: Internet Explorer 6, 7 and Surf this TAB height is out of control, beyond their own setting height

Frequency of encounter: 60%

Solution: Set overflow: Hidden for tags out of height; Or set the line height to be less than the height you set.

Note: this is usually the case with labels with small rounded backgrounds. The reason for this is that browsers prior to IE8 gave tags a minimum default line height. Even if your label is empty, the label will still be the default line height.

5. The window. The location. The problem of href

In Internet Explorer or Firefox 2.2. x, you can use window.location or window.location.href. In Firefox1.5.x, only window.location can be used.

Frequency of encounter: 90%

Solution: Use window.location instead of window.location.href

Note: We often need to jump to the page, which is also a common problem we will encounter in the process of jump

6. The minimum label height min-height is incompatible

Symptom: Because minheight is an incompatible CSS property, setting minheight does not work well across browsers

Chance of encounter: 5%

Solution: If we want to set a minimum label height of 200px, we need to set it to: {min-height:200px; height:auto ! important; height:200px; overflow:visible; }

Note: in the front end of B/S system, there are many cases where we have this requirement. When the content is less than a value (such as 300px). The height of the container is 300px; When the content height is greater than this value, the container height is pushed up instead of scrolling. This is where we face this compatibility issue.

7. Transparency is CSS compatible

 

.transparent_class { filter:alpha(opacity=50); Moz - opacity: 0.5; - KHTML - opacity: 0.5; Opacity: 0.5; }Copy the code

If we are familiar with the default attributes of tags, we will have a good understanding of why compatibility problems occur and how to resolve them.

IE6 recognizes hackers as underscores and asterisks

Hacker is an asterisk *

For example, a CSS setting like this:

height:300px; height:200px; _height:100px; IE6 reads height:300px as 300px; Reading on, IE6 also knows heihgt, so when it reads *height:200px, it overwrites the previous conflict setting and thinks the height is 200px. Reading on, IE6 also knows _height, so it overwrites the 200px setting and sets the height to 100px.

IE7 and Surf are the same and read down from a height of 300px. They stop when they get to *height200px because they don’t know _height. So they parse the height to 200px, and the rest of the browser only knows the first height:300px; So they’ll parse the height to 300px. The order of writing is important because conflicting attributes of the same priority override the previous one.

8. The minimum label height setting min-height is incompatible

Symptom: Because minheight is an incompatible CSS property, setting minheight does not work well across browsers

Chance of encounter: 5%

Solution: If we want to set a minimum label height of 200px, we need to set it to: {min-height:200px; height:auto ! important; height:200px; overflow:visible; }

Note: in the front end of B/S system, there are many cases where we have this requirement. When the content is less than a value (such as 300px). The height of the container is 300px; When the content height is greater than this value, the container height is pushed up instead of scrolling. This is where we face this compatibility issue.

9. Td wrap problem

Symptom: The table width is fixed and TD wraps automatically

Solution: Set Table to Table-layout: fixed, TD to word-wrap: break-word

10. Images are spaced by default

Symptom: Some browsers have a default spacing when several IMG tags are placed together, and the wildcards mentioned in Problem 1 do not work.

Chance of encounter: 20%

Solution: Use the float property for the IMG layout

Note: Since the IMG tag is an inline attribute tag, the IMG tag will be placed on a line as long as it is within the width of the container, but some browsers will have a space between the IMG tags. Remove that spacing and use float is the way to go.

11. If the label height is less than 10px, it will exceed the preset height in Internet Explorer 6 and Internet Explorer 7

Solution: Set overflow: Hidden for tags that exceed height, or set line-height to a value less than your set height

12. Opacity cannot be used in Internet Explorer 9

Solution:

opacity: 0.5;
filter: alpha(opacity = 50);
filter: progid:DXImageTransform.Microsoft.Alpha(style = 0, opacity = 50);
Copy the code

Js article

1. Keyboard eventskeyCodeCompatibility writing

var inp = document.getElementById('inp')
var result = document.getElementById('result')

function getKeyCode(e) {
  e = e ? e : (window.event ? window.event : "")
  return e.keyCode ? e.keyCode : e.which
}

inp.onkeypress = function(e) {
  result.innerHTML = getKeyCode(e)
}
Copy the code

2. Find the compatible writing method of window size

// The size of the viewable area of the browser window (excluding toolbars and scrollbars)
/ / 1600 * 525
var client_w = document.documentElement.clientWidth || document.body.clientWidth;
var client_h = document.documentElement.clientHeight || document.body.clientHeight;

// The actual width and height of the page content (including the sidebar and scrollbar)
/ / 1600 * 8
var scroll_w = document.documentElement.scrollWidth || document.body.scrollWidth;
var scroll_h = document.documentElement.scrollHeight || document.body.scrollHeight;

// The actual width and height of the page content (excluding toolbar and scrollbar edges)
/ / 1600 * 8
var offset_w = document.documentElement.offsetWidth || document.body.offsetWidth;
var offset_h = document.documentElement.offsetHeight || document.body.offsetHeight;

// Roll height
var scroll_Top = document.documentElement.scrollTop||document.body.scrollTop;
Copy the code

3. Compatible writing of DOM event handlers

var eventshiv = {
    / / the event compatibility
    getEvent: function(event) {
        return event ? event : window.event;
    },

type compatible
getType: <span class="hljs-keyword">function</span>(event) {
    <span class="hljs-built_in">return</span> event.type;
},

/ / target compatible
getTarget: <span class="hljs-keyword">function</span>(event) {
    <span class="hljs-built_in">return</span> event.target ? event.target : event.srcelem;
},

// Add an event handle
addHandler: <span class="hljs-keyword">function</span>(elem, <span class="hljs-built_in">type</span>, listener) {
    <span class="hljs-keyword">if</span> (elem.addEventListener) {
        elem.addEventListener(<span class="hljs-built_in">type</span>, listener, <span class="hljs-literal">false</span>);
    } <span class="hljs-keyword">else</span> <span class="hljs-keyword">if</span> (elem.attachEvent) {
        elem.attachEvent(<span class="hljs-string">'on'</span> + <span class="hljs-built_in">type</span>, listener);
    } <span class="hljs-keyword">else</span> {
        // Here due to. 'on'
        elem[<span class="hljs-string">'on'</span> + <span class="hljs-built_in">type</span>] = listener; }},// Remove the event handle
removeHandler: <span class="hljs-keyword">function</span>(elem, <span class="hljs-built_in">type</span>, listener) {
    <span class="hljs-keyword">if</span> (elem.removeEventListener) {
        elem.removeEventListener(<span class="hljs-built_in">type</span>, listener, <span class="hljs-literal">false</span>);
    } <span class="hljs-keyword">else</span> <span class="hljs-keyword">if</span> (elem.detachEvent) {
        elem.detachEvent(<span class="hljs-string">'on'</span> + <span class="hljs-built_in">type</span>, listener);
    } <span class="hljs-keyword">else</span> {
        elem[<span class="hljs-string">'on'</span> + <span class="hljs-built_in">type</span>] = null; }},// Add the event broker
addAgent: <span class="hljs-keyword">function</span> (elem, <span class="hljs-built_in">type</span>, agent, listener) {
    elem.addEventListener(<span class="hljs-built_in">type</span>.<span class="hljs-keyword">function</span> (e) {
        <span class="hljs-keyword">if</span> (e.target.matches(agent)) {
            listener.call(e.target, e); // this points to e.target}}); },// Cancel the default behavior
preventDefault: <span class="hljs-keyword">function</span>(event) {
    <span class="hljs-keyword">if</span> (event.preventDefault) {
        event.preventDefault();
    } <span class="hljs-keyword">else</span> {
        event.returnValue = <span class="hljs-literal">false</span>; }},// Prevent events from bubbling
stopPropagation: <span class="hljs-keyword">function</span>(event) {
    <span class="hljs-keyword">if</span> (event.stopPropagation) {
        event.stopPropagation();
    } <span class="hljs-keyword">else</span> {
        event.cancelBubble = <span class="hljs-literal">true</span>; }};Copy the code

Mobile terminal compatible with browser

CSS article

1. Ios has some cases on non-clickable elements

Symptom: Some cases on ios listen for click events on non-clickable elements (label, span), iso does not trigger

Chance of encounter: 90%

Add cursor: pointer to CSS to create cursor.

2. Don’t let your Android phone recognize your email

<meta content="email=no" name="format-detection" />

3. Prohibit iOS from identifying long numbers as phone numbers

<meta content="telephone=no" name="format-detection" />

4. Disable iOS Windows

-webkit-touch-callout:none

5. Eliminate the Transition screen

-webkit-transform-style: preserve-3d; /* Sets how embedded elements are rendered in 3D space: keep 3D*/
-webkit-backface-visibility: hidden; /*(sets whether the back of the converted element is visible from the user: hidden)*/
Copy the code

6. Disable text selection for ios and Android users

-webkit-user-select:none

7.CSS animation page flashes white and animation freezes

# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # Enabling Hardware Acceleration

-webkit-transform: translate3d(0.0.0);
-moz-transform: translate3d(0.0.0); 
-ms-transform: translate3d(0.0.0); 
transform: translate3d(0.0.0);
Copy the code

8. The defect is fixed

  • Fixed elements in ios are prone to positioning errors, which affects the positioning of fixed elements when the soft keyboard is displayed
  • Fixed performance on Android is better than that on iOS. When soft keyboard pops up, fixed element positioning will not be affected
  • Position :fixed is not supported in ios4
  • Solution: Use the iScroll plugin to solve this problem

9. Prevent the font size from automatically adjusting when the screen is rotated

html.body.form.fieldset.p.div.h1.h2.h3.h4.h5.h6 {
-webkit-text-size-adjust:none;
}
Copy the code

10.Input placeholder will have text that is placeholder

The input placeholder will have a text position that is a bit too high: set line-height to the PC side of the placeholder, and set line-height to normal for the mobile side

11. Compatibility processing of CALC

The calc variable in CSS3 must be prefixed with -webkit- in iOS6 browsers. The -moz- prefix is no longer required in FF browsers.

The Android browser still doesn’t support calc, so add a conservative size before:

div { 
    width: 95%; 
    width: -webkit-calc(100% - 50px); 
    width: calc(100% - 50px); 
}
Copy the code

 

12. Change ugly click highlighting on mobile, both iOS and Android:

* {- its - tap - highlight - color: rgba (0,0,0,0); }

 

13. overflow: auto; IOS phones are stuck scrolling

-webkit-overflow-scrolling: touch; // Have rebound effect

Js article

1. The click event of IOS mobile terminal has a corresponding delay of 300ms

Symptom: Web pages on mobile devices have a delay of 300ms, which often causes button click delay or even click failure.

Reason: This is due to the distinction between single-player events and double-click screen zoom history.

Chance of encounter: 100%

Solution:

  • Fastclick solves the 300ms delay for click events on mobile phones
  • Zepto’s Touch module, tap events are also designed to solve the lag problem at click
  • The corresponding sequence of touch screen is TouchStart –> TouchMove –> TouchEnd –>click. The onTouchStart event can also be bound to speed up the response of the event and solve the 300ms delay problem

2. The input box at the bottom of H5 is blocked by the keyboard

Symptom: H5 page has a very painful problem is that when the input box is at the bottom, after clicking the soft keyboard input box will be blocked.

var oHeight = $(document).height(); // The current height of the browser
$(window).resize(function(){ 
    if($(document).height() < oHeight){ 
        $("#footer").css("position"."static"); 
    }else{$("#footer").css("position"."absolute"); }});Copy the code

3. When you enter English using the Chinese input method in iOS, one sixth of a space may appear between letters

Value = this.value. Replace (/\u2006/g, “);

4. Round-trip cache problems

Click back in the browser, sometimes js is not automatically executed, especially in Mobilessafari. This is related to the round-trip cache (BFCache).

Onunload = function(){};

I hope you can solve compatibility problems quickly