As a front-end engineer who has worked on several H5 projects, it is inevitable that there will be some compatibility issues during the development process. Now I will sum up these problems one by one, and give the principle of pit generation, and the conventional pit filling scheme at the present stage. Hope to help front-end partners.

Mobile Terminal Experience Optimization Experience Summary and Practice (important)

Borrow from the discussion on experience that everyone is a product manager: when technology is no longer the core competitiveness of products, the essence of product competition is the competition for user experience.

Considering that the vast majority of apps on the market are Native+H5 combined applications, the author will summarize how to optimize experience from the Native end and H5 end respectively.

1. Native end experience optimization

Should have the following basic characteristics:

1) Start fast

2) Smooth interaction without delay

3) There is an offline cache

4) Support weak network environment

5) Friendly user prompts

Startup optimization, memory optimization, UI rendering optimization, network optimization, etc. The optimization of memory and UI rendering is mainly aimed at the lag problem. A key object involved in network optimization is cache and weak network support.

Memory optimization

Leakcanary can be used for automatic detection. For further analysis, you can use AndroidStudio to manually dump the memory and use MAT to analyze and find potential memory leak objects.

Memory optimization pays attention to memory leaks as well as jitter, which is usually caused by a large number of frequently created objects.

UI Rendering optimization

UI rendering performance is related to the smoothness of APP. If a drawing is not completed within 16ms, frames will drop, giving a feeling that the page is stuck and the response is not timely.

2. Accelerated optimization of H5 page

Three directions can be optimized:

1) Blank screen time of page startup

2) Interactive experience of H5 page, such as response fluency

3) Page rendering performance

From the perspective of the front end, there can be the following optimization methods:

  • Resource compression, the front end has mature tools to generate JS, CSS and other products for compression, if necessary, you can also consider gZIP compression, to obtain a greater compression ratio.

  • Resource request merge, too many scattered resource packages will generate too many network requests, but can not be merged at will, the best way is to divide according to the page or module, and configure async property to load script asynchronously.

  • Configuring the browser cache, including strong cache and negotiation cache, can greatly reduce network latency and server stress.

  • Load on demand, for single-page applications, it is not reasonable to download all the resources of the entire site on the home page. Using load on demand (lazy loading) can effectively improve the performance of the home page.

  • The skeleton screen is also an important means of optimizing the first screen of a page on the mobile terminal. In the case that the page data is not ready, compared with the boring white screen, the skeleton screen can give users a good sensory experience. However, how to generate a skeleton screen with high quality is also a difficulty, and it is necessary to consider ROI comprehensively to choose whether to use the skeleton screen.

First, mobile terminal development foundation -HTML direction

1, call system functions – call, send SMS, email

Use the three communication functions of phone/SMS/email that can call mobile devices quickly, and use the gallery/file that can call mobile devices quickly.

<! - call - > < a href = "tel: 10086" > call to 10086 little sister < / a > <! - send SMS - > < a href = "SMS: 10086" > send text messages to 10086 little sister < / a > <! <a href="mailto:[email protected]"> </a> <! - choose the pictures or take photographs - > < input type = "file" accept = "image / *" > <! - select the video or shoot video - > < input type = "file" accept = "video / *" > <! <input type="file" multiple>Copy the code

2. Ignore automatic recognition (common)

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

3. Pop-up numeric keypad (commonly used)

<! <input type="tel"> <! <input type="number" pattern="\d*">Copy the code

4. Disable page zooming (common)

With the popularity of smartphones, many websites offer both desktop and mobile versions of browsing, so there is no need to double click to zoom in and out of the page. Disabling page zooming ensures that mobile browsers can display all page layouts without missing a page.

<meta name="viewport" content="width=device-width, user-scalable=no, initial-scale=1, minimum-scale=1, maximum-scale=1">
Copy the code

5. Disable page caching (common)

Cache-control specifies the caching mechanism for requests and responses. Disable this if you don’t want to use browser caching.

<meta http-equiv="Cache-Control" content="no-cache">
Copy the code

6. Do not capitalize letters

Sometimes when you enter text in the input field, the default uppercase correction will be enabled, that is, the input lowercase letter will be automatically corrected to uppercase. Directly declare autocapitalize=off and autocorrect=off.

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

7. Configure for Safari

<! <meta name="apple-mobile-web-app-capable" content="yes"> <meta name="apple-mobile-web-app-capable" content="yes"> -- Change Safari always, optional default/black/ black-always, <meta name="apple-mobile-web-app-status-bar-style" content="black"> <meta name="apple-mobile-web-app-status-bar-style" content="black"> <link rel="apple-touch-startup-image" href="pig.jpg" media="(device-width: 375px)"> <! <link rel="apple-touch-icon" sizes="76x76" href="pig.jpg"> <! <link rel="apple-touch-icon-precomposed" href="pig.jpg">Copy the code

Second, mobile development foundation -CSS direction

1, support elastic rolling (commonly used)

Non-element scrolling may stall on The MAC, but not on Android. Optimize elastic scrolling by declaring overflow-scrolling:touch and calling system native scrolling events to increase scrolling fluency.

body {
    -webkit-overflow-scrolling: touch;
}
.elem {
    overflow: auto;
}
Copy the code

2. Forbid rolling propagation (basic-advanced)

Unlike desktop browsers, mobile browsers have a strange behavior. When the page contains multiple rolling areas, if there is still rolling momentum after rolling a region, the remaining momentum will be transmitted to the next rolling area, causing the region to also roll. This behavior is called “rolling propagation.”

You can ban it if you don’t want it to happen.

.elem {
    overscroll-behavior: contain;
}
Copy the code

3, prohibit screen jitter (basic – advanced)

For some pages with sudden appearance of scroll bars, there may be adverse effects of left and right jitter. In a scroll container, open the popover to hide the scroll bar, close the popover to show the scroll bar, and move back and forth to make the screen shake. Declaring the padding-right of the scroll container to be the width of the scroll bar can eliminate this effect.

The width of the scroll bar may vary from mobile browser to mobile browser and may not even occupy the same position. You can calculate the width of the scroll bar indirectly by using the following method. 100vw is the window width, 100% is the scroll container content width, subtract is the scroll bar width, no problem dynamic calculation.

body {
    padding-right: calc(100vw - 100%);
}
Copy the code

4. Long press is prohibited

Sometimes you do not want users to click the link, make a call, send an email, save a picture or scan the QR code by pressing the element call menu.

Sometimes you don’t want users to copy and paste stolen copy. Declare user-select: None to prevent users from holding down and selecting copy.

* { /* pointer-events: none; */ user-select: none; /* Disable long press to select text */ -webkit-touch-callout: none; }Copy the code

But declaring user-select: None makes and unable to enter text, excluding user-select:auto.

input,
textarea {
    user-select: auto;
}
Copy the code

5, prohibit font adjustment (common)

While rotating the screen may change the font size, declare text-size-adjust:100% to leave the font size unchanged.

* {
    text-size-adjust: 100%;
}
Copy the code

6. Beautify scrolling placeholders

The scrollbar style is too ugly to want to customize, ::-webkit-scrollbar-* to help you. Remember the following three key words to be flexible.

  • [x] :: -webkit-scrollBar: indicates the whole part of the scrollbar

  • [x] ::-webkit-scrollbar-track: indicates the track part of the scrollbar

  • [x] “:: -webkit-scrollBar-thumb” : Part of the slider

    ::-webkit-scrollbar { width: 6px; height: 6px; background-color: transparent; } ::-webkit-scrollbar-track { background-color: transparent; } ::-webkit-scrollbar-thumb { border-radius: 3px; background-image: linear-gradient(135deg, #09f, #3c9); }

7. Identify text newlines

Most of the time you’ll use JS newline text, and that’s really Out. If the interface returns a field containing \n or, do not replace it, declare white-space:pre-line to the browser for line breaking.

* {
    white-space: pre-line;
}
Copy the code

8. Monitor screen rotation (Basics – User Experience)

/* @media All and (orientation: portrait) {/* custom style */} /* @media all and (orientation: portrait) Landscape) {/* Custom style */}Copy the code

9, Before, after

(Input, img, iframe, etc., cannot contain other elements, so you cannot insert content through pseudo-elements.)

Iii. Frequently Asked Questions (Project practice – Important)

1, H5 page – iPhoneX bangs screen adaptation

Bangs screen display

Page adaptation code

1) We need to add a new value to the meta of the page before we can adapt the screen:

<meta name="viewport" content="viewport-fit=cover">
Copy the code

2) Setting height:

Padding-top: constant(safe-area-inset-top); paddING-top: constant(safe-area-inset-top); padding-top: env(safe-area-inset-top); Padding-bottom: constant(safe-area-inset-bottom); padding-bottom: constant(safe-area-inset-bottom); padding-bottom: env(safe-area-inset-bottom);Copy the code

Extensions: CSS functions env() and constant()

Both of these functions are WebKit CSS functions that can be used directly with variable functions and are only supported in the WebKit kernel.

  1. Env: must be supported on ios >= 11.2;

  2. Constant function: must be supported by ios < 11.2

* New feature in iOS11, a CSS function in Webkit for getting the distance between a security zone and a boundary, with four predefined variables (in px) :

  1. Safe-area-inset-left: indicates the distance between the security zone and the left border, applicable in landscape mode.

  2. Safe-area-inset-right: indicates the distance between the security zone and the right border, which is applicable in landscape mode.

  3. Safe-area-inset-top: The distance between the security zone and the top edge is 44px, iphone6 series 20px.

  4. Safe-area-inset-bottom: The distance between the security zone and the bottom boundary is 34px in portrait mode.

The core of adaptation is that constant() can be used to get unsafe margins, and the padding or margin can be used to control page elements to avoid unsafe areas.

* Accurate to the model to do adaptation

// iphoneX, iphoneX, iphone11 pro@media only screen and (device-width: 4px; 375px) and (device-height: 812px) and (-webkit-device-pixel-ratio: 3), // iPhone 12, iPhone 12 Pro only screen and (device-width: 390px) and (device-height: 0) And (-webkit-device-pixel-ratio:3), // iPhone Xs Max, iphone11 Pro Max only screen and (device-width: 4px) 414px) and (device-height: And (-webkit-device-pixel-ratio:3), // iPhone XR, iPhone 11 only screen and (device-width: 414px) and (device-height: 896px) and (-webkit-device-pixel-ratio:2), // iphone 12 Pro Max only screen and (device-width: 428px) and (device-height: 926px) and (-webkit-device-pixel-ratio:3){// constant(safe-area-inset-top); Padding-top: env(safe-area-inset-top); padding-top: env(safe-area-inset-top); Padding-bottom: constant(safe-area-inset-bottom); padding-bottom: constant(safe-area-inset-bottom); Padding-bottom: env(safe-area-inset-bottom); }}Copy the code

2. Adaptive – CALC is used to dynamically calculate the length value

The height is calculated using the CSS3 function calc()

Calc () = calc(four operations) used to dynamically calculate the length value.

Leave a space before and after the operator, for example: width: calc(100% — 10px);

A new feature in CSS3 that specifies the length of an element. (Solve the problem of breaking containers)

// Adjust the middle height. Mid-set {top: 176px; bottom: 98px; height: calc(100vh - 314px); } // Width :-webkit-calc(100%-9px);Copy the code

Expanding knowledge:

1) Viewport: a viewport. Vw Viewport width, 1vw is equal to 1% of the Viewport width

Vh Viewport height, 1vh is equal to 1% of the Viewport height

Height :100% vs. height:100vh

Vh is 1% of the height of the current screen visibility, that is

height:100vh == height:100%;

But when the element has no content, set height:100%, the element will not be stretched, and the height is 0,

But if you set height to 100vh, the element will be spread out at the same height.

3. Prohibit highlighting (basic – Common)

Effect: In some Android systems, how to remove the border generated when elements are clicked

Touch elements appear as translucent gray masks.

A, button, input, textarea {- its - tap - highlight - color: rgba (0,0,0,0); -webkit-user-modify:read-write-plaintext-only; }Copy the code

Some models can’t be removed, like the Mi 2

There is another option for button classes, instead of using an A or input tag, use a div tag.

4. Beautify the appearance of forms (Basic – Common)

Appearance: None to help you customize the form element style.

button,input,select,textarea { appearance: none; /* Custom style */}Copy the code

Such as:

The input box has an inner shadow at the top by default on ios, but not on Android.

The solution is to add the following style to the input:

input[type="text"] {
  -webkit-appearance: none;
}
Copy the code

5. Vertical direction of centering text on mobile terminal (basic – common)

Students with obsessive-compulsive disorder always feel that the text position of the input box is on the whole, and the feeling is not centered. In the desktop browser, declare line-height equal to height. In the mobile browser, declare line-height equal to height.

input {
    line-height: normal;
}
Copy the code

In the development process, found in the Andriod machine up and down center problem, text bias.

Methods that have been tried:

1) line – height

2) the padding

3) the flex

All three methods have been tried to no avail.

When lang=en, the button text is upward, and when lang=en, the button text is downward

.box{    
  display: table-cell;    
  text-align: center;    
  vertical-align: middle; 
}
Copy the code

6, ios compatible input cursor height

The cursor in the input box works fine on An Android phone, but the height of the cursor is the same as the height of the parent box when the input is clicked on an iPhone.

Use padding to support the height and line-height content, not the line-height property.

7. Automatic adaptation to background (basic – common)

Use REM layout to declare an element background. In most cases background-size is declared as cover. It is possible that on a mobile device with the corresponding resolution of the design, the background will fit perfectly, but on a mobile device with another resolution, there will be a gap between 1px and NPX left and right.

At this point, background-size is declared to be 100% 100%, which changes with width and height. Anyway, width and height are the actual measured dimensions.

.elem {
    width: 1rem;
    height: 1rem;
    background: url("pig.jpg") no-repeat center/100% 100%;
}
Copy the code

8. Beautify input placeholders (Basic – Common)

Input box placeholder text is too ugly, ::-webkit-input-placeholder to help you.

input::-webkit-input-placeholder {
    color: #66f;
}
Copy the code

9. The rounded corners of the input box on mobile ios become right angles

But on ios, the input box still has rounded corners,

For Android and PC, there are right angles.

border-radius: 0;
Copy the code

10. Disable cSS3 properties (Important)

Function:

  1. Prevent user clicks from having any effect;

  2. Prevents display of the default mouse pointer;

  3. Prevents CSS hover and active state changes from triggering events.

  4. Prevents events triggered by JavaScript click actions;

    pointer-events:none;

11, onInput event, real-time verification

1) Most mobile phones will input English and a single Chinese character in this order, and only execute the input event once when entering multiple Chinese characters. Test machine (Mi 3, Lenovo, GUANG Xin S5), click the special key enter or go will also execute keyDown, keyPress, keyUp

2) Samsung is special, clicking any key will have two keydown, two keyUp and one input

Conclusion:

1. Keyup is not executed when multiple Chinese characters are entered

2. You do not need to run keyUp for special keys

3. Samsung performs keyup multiple times

Improved events: Use onInput events

Reference: see more webpage version and WAP version of the input event, Tencent WAP version does not have this function.

In addition, the onchange event is excluded, which is executed only if the focus is lost.

Such as:

Text box Counts the number of words in real time

Keydown event and onchange event

The onchange event must be triggered when the form loses focus, so real-time statistics cannot be achieved.

Keydown seems to do the trick, but when you copy and paste with the mouse, you’ll notice that the number of words has changed, but the event is not monitored, which is a bit of a bug.

12. Enable GPU hardware acceleration (Basic – Common)

Graphics Processing Unit (GPU). GPU is a concept relative to CPU. As graphics processing becomes more and more important in modern computers, a special graphics core processor is needed. Enable hardware acceleration with CSS in the browser to enable GPU functions.

Hardware acceleration (*)

webkit-transform: translateZ(0); Its - transform: translate3d (0, 0);Copy the code

Both of these properties turn on GPU hardware acceleration mode, which allows the browser to switch from CPU to GPU when rendering animations.

Page optimization scheme :(important)

1. Hardware acceleration

2. Interactions are too complex

3, integrate images, integrate CSS, JS

4. The server starts Gzip compression

The best advice is to delete the scene, delete the content

Note: To improve web page performance, we should reduce the frequency and cost of “rearrangement” and “redraw”, and trigger as few re-renders as possible.

Through its – transform: transition3d/translateZ open GPU hardware acceleration of the scope of application:

1. Pages animated with lots of large images (especially PNG24 images).

2, the page has a lot of large size pictures and CSS zoom processing, the page can scroll.

3, use background-size:cover to set the large size background image and the page can be scrolled.

4, write a lot of DOM elements to CSS 3 animation (transition/transform/keyframes/absTop&Left)

5. When using a lot of PNG images to splice CSS Sprite.

Accept =”image/* (important)

<input type="file" accept="image/*" capture="camera">
<input type="file" accept="video/*" capture="camcorder">
<input type="file" accept="audio/*" capture="microphone">
Copy the code

Capture allows you to capture default system devices, such as cameras. Camcorder — video camera; Microphone – recording.

14. Multi-background effect

background:url(.. /img/logo.png) no-repeat 20px 40px,url(.. /img/bg1.jpg) no-repeat center; background-size:107px auto,cover;Copy the code

15. 1-pixel problem – Precompiled SASS (common)

@mixin border-1px($color) { &::after { content: ''; display : block; position: absolute; left: 0; right: 0; bottom: 0; height: 1px; background: $color; The transform: scaleY (0.5); }} // use @include border-1px(# DDD);Copy the code

16. Control overflow text – precompile SASS (common)

@mixin ellipsis($line) { display: -webkit-box; -webkit-box-orient:vertical; overflow: hidden; -webkit-line-clamp: $line; } // Beyond ellipsis use @include ellipsis(1);Copy the code

17, need to go deep -iframe scroll bar can not drag bug (signed agreement)

<div class="signatureContet" id="signatureContet" :style="'height:' + wrapperHeight + 'px'"> mounted() { this.timeInit =  setTimeout(() => { this.wrapperHeight = this.mode == 2 ? window.innerHeight - 40 : window.innerHeight - 40 - 44; this.clientWidth = window.innerWidth; this.clientHeight = window.innerHeight; document.getElementById("myIframe").style.height = document.getElementById("myIframe").contentDocument.body.offsetHeight  + 100 + "px"; }, 200); }Copy the code

Iframe embedded web page cannot scroll on mobile terminal and multiple scroll bar problems

Blog.csdn.net/baidu_41828…

18, mobile terminal page popup scroll, the page also scroll solution

@touchmove="e => { e.preventDefault(); }"
Copy the code

Four, mobile terminal pit log (principle and source code)

1. 1px questions

performance

In mobile terminal Web development, the border is set as 1 pixel in the UI design draft. If border:1px appears in the front end development process, the test will find that 1px is relatively thick in retina display models, which is the classic 1px pixel problem on mobile terminal.

Question why

DevicePixelRatio: DPR =window.devicePixelRatio, which is the ratio of physical pixels to logical pixels of the device. On a Retina phone, with a DPR of 2 or 3, the 1px width written in CSS maps to 2px or 3px width on a physical pixel.

The solution

*1. 0.5px scheme

In IOS8+, apple series already support 0.5px, can be handled with media query.

/* This is CSS mode */

.border { border: 1px solid #999 } @media screen and (-webkit-min-device-pixel-ratio: 2) { .border { border: */ @media screen and (-webkit-min-device-pixel-ratio); / / @media screen and (-webkit-min-device-pixel-ratio) 3) {. Border {border: 0.333333px solid #999}}Copy the code

On IOS7 and below and other systems like Android, 0.5px will be displayed as 0px. Then we need to figure out how to do it, and in fact find hacks.

The solution is to check with JavaScript if the browser can handle a border of 0.5px, and if so, add a class to the HTML tag element.

if (window.devicePixelRatio && devicePixelRatio >= 2) { var testElem = document.createElement('div'); testElem.style.border = '.5px solid transparent'; document.body.appendChild(testElem); } if (testElem.offsetHeight == 1) { document.querySelector('html').classList.add('hairlines'); } document.body.removeChild(testElem); $(document).ready(function() {})Copy the code

Then, extremely thin border styles are easy:

div { border: 1px solid #bbb; }. Hairlines div {border-width: 0.5px; }Copy the code

** Advantages: ** simple, doesn’t require much code.

** Disadvantages: ** not compatible with Android devices, iOS 7 and below.

* 2. Pseudo-classes + transform

Principle: Remove the border of the original element, then use :before or :after to redo the border and reduce the scale of the transform by half. The original element is positioned relative to the original element, and the new border is positioned absolutely.

@media (-webkit-min-device-pixel-ratio: 2) {. Border -1px::after {width: 200%; height: 200%; The transform: scale (0.5); transform-origin: 0 0; }}Copy the code

** Advantages: ** All scenarios can be satisfied, support rounded corners (pseudo-classes and ontology classes need to add border-radius).

** Disadvantages: ** Also has a lot of code and may require multiple layers of nesting for elements that already use pseudo-classes (such as Clearfix).

2. IOS doesn’t swipe smoothly

performance

Swiping up and down the page creates a stutter, and when your finger leaves the page, the page immediately stops moving. The overall performance is not smooth sliding, no sliding inertia.

Question why

In iOS 5.0 and later, there are two values for sliding: auto and touch. The default is auto.

-webkit-overflow-scrolling: touch; /* When the finger is removed from the screen, it keeps scrolling for a while */ -webkit-overflow-scrolling: auto; /* When the finger is removed from the touch screen, scrolling stops immediately */Copy the code

The solution

Global scrolling: the scroll bar is at the top of the body node or above;

Local scrolling: the scroll bar is on a DOM node under the body;

The ios development

Global scrolling: supported by default

Partial scrolling: There is no scroll bar by default, and sliding is dry.

body{-webkit-overflow-scrolling:touch; } (fast scroll and bounce) /* Local scroll dom node */.scroll-el{overflow:auto; }Copy the code

Suggestion: Hang the property on the body to avoid a lot of weird bugs.

3, iOS pull-up boundary pull-down white blank

performance

Hold your finger on the screen and pull it down to create a white area at the top of the screen. Hold your finger on the screen and pull, creating a white area at the bottom.

The reasons causing

In iOS, holding a finger and dragging it up and down triggers the TouchMove event. This event triggers the entire WebView container, which will naturally be dragged, leaving the rest blank.

In the W3C document it says:

The speed of touchMove events is implementation-definable, depending on hardware performance and other implementation details

PreventDefault method, prevent all default actions on the same contact, such as scrolling.

The solution

The monitoring event forbids sliding. By listening to touchMove, slide where sliding is needed and prohibit sliding where sliding is not needed.

. / / the above ios13 did not effect the document body. AddEventListener (' touchmove ', function (evt) {if (! evt._isScroller) { evt.preventDefault(); }}); // This will completely disable TouchMove and cause internal scrolling to fail. document.body.addEventListener('touchmove', function (e) { if(e._isScroller) return; // Filter out elements with scroll containers. e.preventDefault(); }, {passive: false} ); // Passive cannot be omittedCopy the code

4, page zoom in or out of the uncertain behavior

performance

Double-click or open the finger page element with both fingers to zoom in or out.

The reasons causing

HTML itself generates zooming in and out behavior, such as in a PC browser, where pages can be zoomed in and out freely. But on mobile, we don’t need this behavior. Therefore, we need to prohibit this uncertain behavior to improve the user experience.

Principles and solutions

The HTML meta meta tag standard has a medium viewPort property that controls the zoom of a page. It is usually used on mobile devices.

Mobile terminal general writing.

< meta name = "viewport" content = "width = device - width, initial - scale = 1.0" >Copy the code

So maximum-scale, minimum-scale, and user-scalable=no can be used to avoid this problem.

<meta name=viewport  content="width=device-width, initial-scale=1.0, minimum-scale=1.0 maximum-scale=1.0, user-scalable=no">
Copy the code

Width =device-width: indicates the width of the device screen

Initial-scale =1.0: indicates the initial scaling ratio

Minimum-scale =0.5: Indicates the minimum scale

Maximum-scale =2.0: indicates the maximum scale

User-scalable =yes: indicates whether the user can adjust the scaling

Click has 300ms latency and penetration on ios

performance

1, delay: listen to the element click event, click element trigger time delay of about 300ms.

2. Penetration: Click on the mask layer. After the mask disappears, the lower element will be triggered by clicking.

The reasons causing

1. Why is there a click delay?

In safari on iOS, to double – click zoom operation, click 300ms later, if the second click is not performed, click operation. That is, to determine whether the user’s behavior is caused by a double click. However, in the App, a click creates a 300ms delay whether or not you need to double click to zoom.

2. Why does click penetration occur?

When a two-layer element is stacked, the touch event is bound to the upper element and the click event to the lower element. Since click occurs after touch, clicking on the upper element causes the element to disappear, and the lower element triggers the click event, creating the click-through effect.

Principles and solutions

1. Click delay solution

  1. Disable double click scaling

Zooming is banned altogether, and zooming in on an image is not allowed, for example

Application scenario: element page, game page, etc. (note: before ios10, the above is valid)

  1. Pointer Events

    // Disable all gestures on elements (and their non-scrollable descendants) when touch-action is none HTML {touch-action: manipulation; }

Touch actions are also often used to completely resolve the delay of click events caused by support for double click zoom gestures.

  1. Using fastClick

The idea is that when the Touchend event is detected, the DOM custom event immediately simulates the Click event and invalidates the actual event sent by the browser 300 milliseconds later.

FastClick: After the Window load event, call Fastclick.attach () on

window.addEventListener( "load", function() {   
  	FastClick.attach( document.body ); 
}, false );
Copy the code

2, click through

Replacing Click with TouchStart not only solves the click event delay problem, it also solves the penetration problem. Because penetration problems occur when touch and click are mixed.

Used in native

el.addEventListener("touchstart", () => {    
  console.log("ok"); }, false);
Copy the code

6, the soft keyboard will top up the page, not back down

performance

On Android phones, when you click on the Input box, the keyboard pops up and pops up the page, causing the page style to mess up.

When the focus is removed, the keyboard is folded up and the keyboard area is blank without falling back.

The reasons causing

We’re going to have a fixed bottom in our app layout. On some versions of Android, typing in a popup will extract the absolute and fixed elements. Resulting in a smaller viewable area, layout confusion.

Principles and solutions

1, the soft keyboard will top up the page solution, mainly by listening to the page height change, forced to return to the height before the pop-up.

/ / record the viewport height of the original const originalHeight. = the document body. ClientHeight | | document. The documentElement. ClientHeight; window.onresize = function(){ var resizeHeight = document.documentElement.clientHeight || document.body.clientHeight; If (resizeHeight < originalHeight) {/ / restore content area highly}} / / record the viewport height of the original const originalHeight = document. The body. The clientHeight | | document.documentElement.clientHeight; window.onresize = function(){ var resizeHeight = document.documentElement.clientHeight || document.body.clientHeight; If (resizeHeight < originalHeight){Copy the code

2, H5 animation effect (from the document flow), the input box can not input the problem.

Soft keyboard and input box coordination problem (note: when the soft keyboard is popped up, the user cannot input content in the input box) (common)

Js: 1) (” body “). The height ((” body “). The height ((” body “). The height ((” body “). The height ()); // Set the page dynamic height

2) CSS: #wrap{width:100%; height:100%; position:relative; overflow:hidden; } find the parent element

Note: It is recommended not to use fixed position, but absolute position.

The keyboard can not fall back problem appears in iOS 12+ and wechat 6.7.4+, and is a common Bug in the development of wechat H5 **. 八九民运

Compatibility principle, 1. Determine version type 2. Change the scrolling visual area

const isWechat = window.navigator.userAgent.match(/MicroMessenger\/([\d\.]+)/i); if (! isWechat) return; const wechatVersion = wechatInfo[1]; const version = (navigator.appVersion).match(/OS (\d+)_(\d+)_? (\d+)? /); If the device type is iOS 12+ and wechat 6.7.4+, If (+ wechatversion.replace (/\./g, ") >= 674&& +version[1] >= 12) {window.scrollto (0, Math.max(document.body.clientHeight, document.documentElement.clientHeight)); }Copy the code

7. IPhone X series security zone adaptation problem

performance

On both sides of the bangs or at the bottom of the head, bangs block the text, or blank areas with black or white background.

The reasons causing

The iPhone X and its successors all feature bangs and gestures across the screen. The head, bottom and sides all need special treatment. In order to adapt to the special circumstances of iPhone X.

The solution

Set security zones and fill dangerous zones. Do not perform operations or display contents in dangerous zones.

Danger area Finger irregularity area, bottom bar area, left and right trigger area.

  1. Set viewport-fit to cover (iPhoneX must be set to viewport-fit=cover)

  2. Added the safe Area inset variable to the adaptation layer

    Supports (top: env(safe-area-inset-top)){body,.header{padding-top: supports (top: env(safe-area-inset-top)) constant(safe-area-inset-top, 40px); padding-top: env(safe-area-inset-top, 40px); padding-top: var(safe-area-inset-top, 40px); }} /* iPhoneX fills the footer padding-bottom to the bottom */ @supports (bottom: env(safe-area-inset-bottom)){ body, .footer{ padding-bottom: constant(safe-area-inset-bottom, 20px); padding-bottom: env(safe-area-inset-bottom, 20px); padding-top: var(safe-area-inset-bottom, 20px); }

8. Touch for Mobile Development (Important) (Experiment: jquery supports Touch events)

Touchstart (place your finger on the touch screen)

Touchmove (finger moving on the touch screen)

End of touch (remove finger from touch screen)

And of course there’s a ‘TouchCancel,’ which is triggered when the drag is interrupted. (System interruption)

The touchMove e.preventDefault() method undoes the default action associated with the event

Mobile terminal WEB development, Click, Touch,tap events analysis

Compare click and tap

Both trigger when clicked, but on the mobile WEB, click takes 200 to 300 ms, so use tap instead of click as the click event.

On the point penetration of TAP

When using tap of the Zepto framework to move click events in the browser of the device to avoid the delayed response of click events, there is a possibility of point-penetration, that is, clicking triggers click events that are not in the current layer.

Touch Events Touch is for touch events on touch-screen phones. The WebKit kernel of most touchscreen phones today provides a listener for touch events, allowing developers to retrieve information about when a user touches the screen.

The corresponding sequence for touchscreens is TouchStart –> TouchMove –> TouchEnd –> Click