preface

In the usual H5 mobile terminal development, we will inevitably encounter a variety of pits, this article will take you to see how to solve the problem, the article is longer, it is recommended to collect easy to refer to later!

High energy ahead!

On Android, using native video directly results in full screen playback, covering all elements, so use the X5 player. But the X5 player still has a problem. It doesn’t cover elements, but it does add its own effects (a layer of navigation).

<video
  id='live-player'
  controls={false}
  preload="auto"
  playsInline
  mtt-playsinline="True"
  webkit-playsinline='true'
  x5-video-player-type='h5'
  x5-video-orientation='portrait'
  x5-playsinline='true'
/>
Copy the code

This works with x5 player on Android, and the playsInline and WebKit-PlaysinLine properties enable inline playback on iOS. However, setting inline playback compatibility via properties is not very good, so we need to use the iphone-inline-video library and enableInlineVideo(video).

Canvas blurs on retina display

Just scale the brush according to the pixel ratio

run(canvasEl) {
    const canvas = canvasEl;
    const ctx = canvas.getContext('2d');
    const devicePixelRatio = window.devicePixelRatio || 1;
    const backingStorePixelRatio = ctx.webkitBackingStorePixelRatio ||
    ctx.mozBackingStorePixelRatio ||
    ctx.msBackingStorePixelRatio ||
    ctx.oBackingStorePixelRatio ||
    ctx.backingStorePixelRatio || 1;

    const ratio = devicePixelRatio / backingStorePixelRatio;
    if(devicePixelRatio ! == backingStorePixelRatio) {const oldWidth = canvas.width;
      const oldHeight = canvas.height;

      canvas.width = oldWidth * ratio;
      canvas.height = oldHeight * ratio;

      canvas.style.width = `${oldWidth}px`;
      canvas.style.height = `${oldHeight}px`; ctx.scale(ratio, ratio); }},Copy the code

With equal proportions, the image is clear on a PC, but blurry on a mobile phone. Why?

After research, it is found that devicePixelRatio is the fault. Because the resolution of the mobile phone is too small, if the webpage is displayed according to the resolution, it will be very small. Therefore, Apple only displays 480320 in the webpage with 960640 resolution of iPhone 4, so devicePixelRatio = 2; For example, if the width and height of a div is 100100, the background image must be 200200, and then background-size:cont ain; , so that the display of the picture is clearer; The code is as follows:

   background:url(../images/icon/all.png) no-repeat center center;
   -webkit-background-size:50px 50px;
   background-size: 50px 50px;
   display:inline-block; 
   width:100%; 
   height:50px;
Copy the code

Enable or disable the phone number in the automatic identification page;

<meta name="format-detection" content="telephone=no"> 
Copy the code

By default, the device automatically recognizes any string that could be a phone number. Setting telephone=no disables this function, as does not recognizing email and addresses

H5 website input set to type=number problem

H5 webpage input type set to number will generally cause three problems:

Problem 1: The maxLength attribute is not easy to use

<input type="number" oninput="checkTextLength(this ,10)">
<script type="text/javascript">
    function checkTextLength(obj, length) {
        if(obj.value.length > length)  {
            obj.value = obj.value.substr(0, length); }}</script>
Copy the code

Problem 2: The form submission is rounded by default

<input type="number" step="0.01" />// Input type=number automatically generates an up and down arrow. Clicking the up arrow adds a step by default, and clicking the down arrow reduces a step by default. The default step in number is 1, that is, step=0.01. You can enter 2 decimal places, and click the up and down arrows to increase and decrease 0.01 respectively. Step and min must be between min and Max when used togetherCopy the code

Problem 3: Some Android phones have style problems

To remove the default style of input:

input.textarea {
    border: 0; -webkit-appearance: none; // Can also shield the input box weird inner shadow, solve iOS can not change the button style, test also found that after adding this attribute,iOS still have rounded corners by default, but can be usedborder-radiusProperty modification}Copy the code

Select drop down select setting question

Problem 1: Right aligned implementation

Set the following properties

select option {
    direction: rtl;
}
Copy the code

Problem 2: Disable the select default arrow

Select ::-ms-expand {display:none; }Copy the code

Mobile HTML5 Audio autoplay failure

Because the audio or video in the webpage will bring users trouble or unnecessary traffic consumption, so the Apple system and Android system usually prohibit automatic play and JS trigger play, must be triggered by the user to play; Solution idea: first through the user touchstart touch trigger play and pause (let the audio start loading), then use JS operation no problem; Solution code:

document.addEventListener('touchstart'.function () {
    document.getElementsByTagName('audio') [0].play();
    document.getElementsByTagName('audio') [0].pause();
});
Copy the code

CSS animation page flash white, animation stuck, picture confusion problem

1. CSS3 animation should be designed using the synthetic properties transform and opacity whenever possible, instead of using the left and top of position for positioning

2. Enable 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

Floating child elements spread parent element box height (BFC)

Solutions are as follows:

1. Set the parent element to overflow: hidden;

2. Set the parent element to display: inline-block; Etc.

In both cases, the parent of the floating element is changed into a BFC(block-level formatting context) element by setting CSS attributes so that the child element is tall enough to support the parent element. It is best to use method 1, however, because the inline-block element will have some width to support itself

Round-trip caching issues

Browser rollback sometimes does not automatically execute JS, especially in Mobilesafari; This is related to the round-trip cache (BFcache).

window.onunload = function(){};
Copy the code

Positioning of the pit

In IOS, fixed position will be invalid when the soft keyboard is jacked up, so we used absolute in development

Audio and video elements cannot play in ios and Android

<audio src="music/bg.mp3" autoplay loop controls>Your browser doesn't support it yet</audio>// If () {//<audio controls="controls">// If (<source src="music/bg.ogg" type="audio/ogg"></source>
    <source src="music/bg.mp3" type="audio/mpeg"></source>// Play music bg.ogg first, bg.mp3 is not supported</audio>
Copy the code

Here generally can play music, if it is not likely to be limited by wechat

Problem 3: Limitations of wechat

If it is limited by wechat, the wechat interface needs to be called at this time, and the page is introduced first:

< script SRC = "http://res.wx.qq.com/open/js/jweixin-1.0.0.js" > < / script >Copy the code

Then JS writes into the wechat event:

document.addEventListener("WeixinJSBridgeReady", function() {
    document.getElementById('music').play();
}, false);
Copy the code

Summary:

1. The autoplay attribute of the audio element is unavailable on IOS and Android, but works properly on PC

2. The audio element without controls takes up space on IOS and Android, while Chrome does not take up any space on PC

Fault 4:Safari plays automatically

document.addEventListener('touchstart'.function(){   
    audio.play();
}, false);
Copy the code

Ios does not support animation-play-state

H5 page generally has BGM, also will provide a rotating music icon for users to turn on and off music; We want the icon to stop rotating when the user clicks the music button, and then click the icon to continue running the animation along the previous stopped position. Animation-play-state is the easiest way, but ios does not support it

The current solution is that the music icon is responsible for running the animation, and the icon’s parent element is responsible for recording the rotation value when stopped

Ios prevents long-pressing page elements from being selected

Solution: Add style can prohibit users from copying,ios and general Android can solve

-webkit-touch-callout:none; // The system default menu is disabled. -webkit-user-select:none; //webkit browser -khtml-user-select:none; // early browser -moz-user-select:none; / / firefox - ms - user - select: none. //IE10 user-select:none;Copy the code

After adding this code, there will be a problem on IOS, and you will notice that the input box is no longer being entered; -webkit-user-select:none; The solution is to set the input property in the CSS file as follows:

input{ -webkit-user-select:auto; // webKit browser}Copy the code

How to solve the problem of lag/slowness when html5 encounters up and down scrolling bar

First, you might add height: 100% to the HTML and body of the page, which could cause the page to slide slow on IOS.

The solution is: 1. Make HTML and body fixed at 100% (or 100vh), 2. Add a height:100% div inside and set overflow-y: auto; And – its overflow – scrolling: touch;

Overflow-x :auto has a compatibility issue on iOS.

.scroll-box {
  Divs such as modal boxes cannot be placed in this container, otherwise closing modal boxes sometimes does not close */
  height: 100%;
  overflow-y: auto;
  -webkit-overflow-scrolling: touch;
  overflow-scrolling: touch;
}
Copy the code

Click on an element to create a background or border

A, button, input, textarea {- its – tap – highlight – color: rgba (0,0,0,0); -webkit-user-modify:read-write-plaintext-only; //-webkit-user-modify can no longer input multiple characters} or a,button,input,textarea{-webkit-tap-highlight-color: rgba(0,0,0); }

Browser back does not refresh

This happened before, and I’ll mention it here; This happens a little bit more in webView. When you click back, the page is cached, not refreshed. In many cases this is not what you expect, the solution is to use js:

methods1:window.addEventListener('pageshow'.() = > {
  if (e.persisted || (window.performance && 
    window.performance.navigation.type == 2)) {
    location.reload()
  }
}, false); methods2:
window.history.replaceState(null.' '.window.location.href + '? timestamp=' + new Date().getTime());

Copy the code

Onpageshow fires every time a page is loaded, whether it’s loaded from the cache or loaded normally, which is the difference between onLoad and onPagesHow; Persisted determines whether the page is read from the cache

Pages are accessed through history and backwards and forwards. Type a value of 2

Transition Clears the splash screen

-webkit-transform-style: preserve-3d; // Set the embedded element in3How is D space presented: reserved3D
-webkit-backface-visibility:hidden; // Sets whether the back of the converted element is visible to the user: hide -webkit-perspective: 1000;
Copy the code

Resolve active pseudo-class invalidation

<body ontouchstart></body>
Copy the code

Top status bar background color

Apple-mobile-web-app-capable Indicates whether web applications run in full-screen mode. Grammar: <meta name="apple-mobile-web-app-capable" content="yes" name="apple-mobile-web-app-status-bar-style" content="black" />Copy the code

Note: This meta tag will not work unless you have specified full-screen mode using Apple-mobile-web-app-capable first. If content is set to Default, the status bar displays normally. If set to blank, the status bar will have a black background; If set to blank- always, the status bar appears as translucent black. If it is set to Default or Blank, the page is displayed below the status bar, meaning that the status bar occupies the upper part. The page occupies the lower part, and the two do not block each other or are blocked; If set to blank- up, the page always fills the screen, as always covered by a status bar (20px, as opposed to 40px on iphone4 and itouch4’s Retina screen). The default value is default.

Ios zone

Safari 3D transforms ignore the z-index hierarchy

In Safari (Safari on iOS, wechat on iPhone, and Safari on Mac OS X), when we use the 3D Transform, If the ancestor element not overflow: hidden/scroll/auto restrictions, can directly to ignore their own and other elements of z – index cascading order Settings, and direct use of 3 d perspective of the real world. For example, in the scene below, the module inside the red box in the figure uses 3D Transform to rotate the animation. However, in Safari browser, the Z-index of the TWO-DIMENSIONAL code mask layer is ignored and the 3D perspective of the real world is used for rendering. There are overlapping bugs:

Solutions:

Parent, any parent, non-body level, set Overflow: Hidden to restore rendering as in other browsers. An eye for an eye. Sometimes, if the page is too complex and we cannot set overflow:hidden to the parent, we can set the affected element to a large enough translateZ value, such as translateZ(100px).

Blank screen for ios input

This seems to be a problem only in ios9

Workaround: Add relative positioning to the parent element of the input, magic

IOS input keyboard events keyup/ keyDown /keypress are not supported properly

It is found that the IOS input method (either third-party or built-in) can detect English or digital keyup, but not Chinese keyup. After entering Chinese, you need to click the back button to start the search. The solution is to use HTML5 onInput events instead of keyUp, with the following code to achieve a similar effect to Keyup;

1. Changed the state of the input:checkbox or input:radio element selection. Checked property changed

2. The value property of the input:text or textarea element is changed

3. The selected item of the select element is modified, and the input is used when the selectedIndex property changes

<input type="text" id="testInput"> <script type="text/javascript"> document.getElementById('testInput').addEventListener('input', function(e){ var value = e.target.value; //e.target points to the element in the mouse-clicked area when the event is executed; If e.target refers to the child element, if e.target and this refer to the element that the event is bound to,}); </script>Copy the code

IOS keyboard alphabet input, default uppercase solution

Set the following properties

<input autocapitalize="off" autocorrect="off" />
Copy the code

Autocomplete =”off”; autocomplete=”off”; Autocapitalize: automatic capitalization; Autocorrect: error correction

Optimization of font on iOS and OS X (inconsistent font bold on vertical and horizontal screens)

Setting text-size-adjust to None will fix the problem on iOS when the browser resets the font size when it is landscape, but the desktop Version of Safari does not allow font scaling, so the best solution is to set text-size-adjust to 100%

-webkit-text-size-adjust: 100%;
-ms-text-size-adjust: 100%;
text-size-adjust: 100%;
Copy the code

In some cases non-clickable elements such as (label,span) listen for a click event, which is not triggered on ios

In this case, simply add a line of CSS code to the element that does not trigger the click event

cursor: pointer;
Copy the code

Ios supports date() differently

var date =new Date("2019/10/21"); 
Copy the code

Debugging found that 2019/10/21 is the same as 2019-10-21 00:00:00, that is to say, ios is calculated from 0 by default, we do not need to set the following time to 00:00:00

The iOS(Safari) tag binding click event is invalid

The location. Href jump page in ios is blank

In the location.href coat layer setTimeout is solved!

setTimeout(() = > {
       window.location.href = 'www.juejin.im'
}, 0);
Copy the code

Keyboard bounce down bug solution

Click to view

conclusion

The road is long and the road is long