Introduction to the

The previous author has introduced the mobile terminal H5 web development essential knowledge, this article is mainly summarized under the mobile terminal development common problems, to help everyone avoid the pit.

In HTML

Calling system functions

<! -- Dial the phone -->
<a href="tel:10010">Call 10010</a>

<! -- Send SMS -->
<a href="sms:10010">Send a text message to 10010</a>

<! -- Send email -->
<a href="mailto:[email protected]">Email Randy</a>

<! -- Select photo or Take photo -->
<input type="file" accept="image/*" />

<! Select Video or Shoot Video -->
<input type="file" accept="video/*" />

<! -- Select file -->
<input type="file" />

<! -- Select multiple files -->
<input type="file" multiple />
Copy the code

Ignore automatic identification

Sometimes the auto-id of your phone or email can get annoying, so we can turn it off.

<! -- Ignore auto-id calls -->
<meta name="format-detection" content="telephone=no" />

<! -- Ignore automatic mailbox recognition -->
<meta name="format-detection" content="email=no" />

<! Ignore auto-id phone and email -->
<meta name="format-detection" content="telephone=no, email=no" />
Copy the code

Pop-up numeric keypad

Note here, the system needs to use the native keyboard will take effect, can not use sogou and other input methods, otherwise only the corresponding input method will appear numeric keyboard.

<! -- Pure numbers with # and * -->
<input type="tel">

<! -- Pure numbers -->
<input type="number" pattern="\d*">
Copy the code

Internet Explorer and Chrome of the latest version are preferred

<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1" /> 
Copy the code

Disable page caching

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

Turn off uppercase

When we use the keyboard to enter English characters in the input box, the general first letter will be automatically capitalized, if not necessary can be turned off.

<input type="text" autocapitalize="off" />
Copy the code

Turn off automatic input correction

As well as automatically capitalizing English input, IOS also has a feature that automatically corrects input by default, so users often have to do it twice. If you don’t want to turn this feature on, you can turn it off using the input attribute.

<input type="text" autocorrect="off" /> 
Copy the code

Disable page zooming

To avoid scaling the page, we can set the user-scalable value of viewport to no, as discussed in the previous article about viewport.

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

Long press to identify the QR code

Sometimes we will receive the demand, is long press the TWO-DIMENSIONAL code to automatically recognize the two-dimensional code, in fact, this is the simplest, is to use the IMG label to display our pictures. Remember not to use a background image, otherwise it won’t work.

CSS aspects

1 px problem

The 1px problem will only appear on the Retina hd screen, since the hd screen uses multiple physical pixels to display one CSS pixel, such as iphone6, since the DPR is 2, 1css pixel will be displayed with two physical pixels, so it looks like the 1px line will be extremely wide.

There are many solutions to the 1px problem, such as background images, shadows, zooming and so on. The only solution I have used before is zooming. The idea is to fix the border and make the whole element bigger and then smaller.

.ele {
    position: relative;
    width: 100px;
    height: 80px;
    &::after {
        content: "";
        position: absolute;
        left: 0;
        top: 0;
        border: 1px solid red;
        width: 200%;
        height: 200%;
        transform: scale(0.5);
        transform-origin: left top; }}Copy the code

If you don’t want to set every element like this, you can use the Lib-flexible solution described in the author’s mobile H5 web development basics to scale the entire page according to the DPR.

Landscape and portrait

The style for certain landscape or portrait scenarios can be set using the @media query below.

/ * * / vertical screen
@media all and (orientation: portrait) {
    /* Custom style */
}

Landscape * / / *
@media all and (orientation: landscape) {
    /* Custom style */
}

Copy the code

Make the iPhone scroll more smoothly

Scrolling on the iPhone may not be smooth at times, so we can add the following attributes to the element.

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

Prohibit to choose

Sometimes we do not want others to long press to save the picture, we can use the following style, let the user long press the picture invalid.

#img1 {
  pointer-events: none; /* wechat browser also needs to attach this attribute to be valid */
  user-select: none;
  -webkit-touch-callout: none;
}
Copy the code

Native form beautification

When we use the native form, the style is ugly, especially with a gray mask. We can use the following style to remove the mask. Do you feel a lot more relaxed?

button.input,
select,
textarea {
  -webkit-appearance: none;
}
Copy the code

How to remove the translucent gray mask generated when the element is clicked

When using the native form, there will be a grey click effect. If you don’t need it, you can use the following style to remove it.

a.button.input.textarea,select {
    -webkit-tap-highlight-color: transparent;
}
Copy the code

Beautify scroll bar

The scrollbar style is too ugly to be customized, we can use the following style properties to customize the style. This is a common style for both PC and mobile.

  • :: -webkit-scrollBar: indicates the whole part of the scrollbar
  • ::-webkit-scrollbar-track: indicates the track part of the scrollbar
  • ::-webkit-scrollbar-thumb: slider part of the scrollbar
::-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(90deg.#09f.#3c9);
}
Copy the code

Beautify placeholders

This is a common style for both PC and mobile. When we need to change the color of the placeholder, we can use the following style.

input::-webkit-input-placeholder {
    color: red;
}
Copy the code

Center the text in the input box

Sometimes even if we set line-height to height, the text will not look centered. We can use the following style.

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

Text overflows ellipses

When we need to display more text with ellipses, we can use the following style. In fact, this is a common style for both PC and mobile.

To use this style, note that the element must be either a block-level element or an inline block-level element with the specified width (that is, display: inline-block).

Single omit

/* Single line ellipsis */
.ellipsis {
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
}
Copy the code

Multi-line omit

/* Multiline ellipsis, which means the number of lines after which the ellipsis appears, uses the following style */
.ellipsis-n {
    display: -webkit-box;
    overflow: hidden;
    text-overflow: ellipsis;
    -webkit-line-clamp: 2; /* This value can be set arbitrarily, for example, 2 means a maximum of two lines, followed by an ellipsis */
    -webkit-box-orient: vertical;
}
Copy the code

Image blur problem

This is similar to the 1px problem, which will only appear on the Retina hd screen. Since the hd screen uses multiple physical pixels to display one CSS pixel, such as iphone6 (750 physical pixels and 375 CSS pixels), since the DPR is 2, 1css pixel will be displayed with two physical pixels. So a 1 pixel image with 2 physical pixels will be blurry.

To solve the root cause of image blur is to use different multiples of images according to different DPR.

@ media query

.avatar{
    background-image: url(randy_1x.png);
}

@media only screen and (-webkit-min-device-pixel-ratio:2) {.avatar{
        background-image: url(randy_2x.png); }}@media only screen and (-webkit-min-device-pixel-ratio:3) {.avatar{
        background-image: url(randy_3x.png); }}Copy the code

image-set

.avatar {
    background-image: -webkit-image-set( "randy_1x.png" 1x, "randy_2x.png" 2x );
}
Copy the code

srcset

Note that the image cannot be processed by Webpack, or converted to Base64, otherwise it will be invalid.

<img src="randy_1x.png" srcset="randy_2x.png 2x, randy_3x.png 3x" />
Copy the code

Js processing

const dpr = window.devicePixelRatio;
const images =  document.querySelectorAll('img');
images.forEach((img) = >{
  img.src.replace(".".`${dpr}x.`);
})
Copy the code

svg

Of course, we can also use SVG images without losing frames, which will automatically stretch and not lose frames regardless of the screen.

<img src="randy.svg" />
Copy the code

JS aspects

Click on the delay

There is a 300ms delay when clicking on a mobile browser.

In 2007, just before the launch of apple’s first Iphone, the company ran into a problem: Websites were designed for large screens that were too small to be viewed properly, so apple engineers made some conventions to fix the problem. The best known of these conventions is double tap to Zoom, which is the source of the 300ms delay. With two quick finger taps on the screen, iOS’s built-in Safari browser zooms the page to its original scale. If the user clicks on a link in iOS Safari. Since the user can double click to zoom or double click to scroll, once the user clicks the screen, the browser can’t immediately determine whether the user actually wants to open the link or whether the user wants to double click. So iOS Safari waits 300 milliseconds to see if the user has clicked on the screen again. Given the success of the iPhone, other mobile browsers have copied most of the conventions of the iPhone’s Safari browser, including double-clicking to zoom, which is now available on almost all mobile browsers. This creates the 300ms delay problem.

There are many solutions to click delay, and the following four are highlighted.

Disable page zooming

We know that the root cause of click delay is page zooming, so we can disable page zooming to solve the problem at the source, but the disadvantage of this solution is obvious, the page cannot be zoomed.

 <! -- 1. Disable scaling user-scalable=no -->
 <meta name="viewport" content="Width = device - width, initial - scale = 1.0, user - scalable = no" />
Copy the code

Change the default viewport width

<meta name="viewport" content="width=device-width" />
Copy the code

Because double click zoom is mainly used to improve the desktop site in the mobile browsing experience, and with the popularity of responsive design, many sites have been adapted and optimized for mobile sitting, at this time there is no need to double click zoom, if you can identify a website is responsive website, Mobile browsers can automatically disable the default double click zoom behavior and remove the 300ms click delay. If the meta tags are set, the browser can assume that the site has been adapted and optimized for mobile, without the need to double click to zoom.

The advantage of this scheme over scheme 1 is that it does not completely disable zooming, but just disables the browser’s default double-click zooming, but users can still zoom through the two-finger zooming operation.

Use zepto

The first solution to click delay in the front end was Zepto from the jQuery era. Most of you probably haven’t used Zepto yet, but it’s actually the mobile version of jQuery. Zepto encapsulates tap events to effectively solve click penetration. We know that the sequence of mobile click events is TouchStart — > TouchMove — > TouchEnd — > click. The TAP event is simulated by listening to the touch event on document (because the click event has a 300ms delay on the mobile side but the touch event has no delay on the mobile side) and bubbling the TAP event onto the document triggers the click event on the simulated mobile side.

While Zepto solves click delay, it also causes click penetration, where if an element actually has a click attached to it, and we know that the event is propagating, click will continue to fire after the TAP event, causing click penetration.

Why not use e.preventDefault() in the touchend event to prevent subsequent events from being triggered? This is related to zepto’s tap event implementation, which listens for touchend events globally, so using e.preventDefault() will affect the actual Touchend event.

Using fastclick

Fastclick is a lightweight library developed by FT Labs to solve the 300-millisecond click delay problem in mobile browsers. The implementation principle of FastClick is that when the Touchend event is detected, the DOM custom event will immediately simulate a click event and block the browser click event after 300ms.

Fastclick is an optimal solution to click latency without causing click penetration. You can check the official documentation for specific usage methods.

A matter of time

The date format yyyY-MM-DD HH: MM :ss is an error to parse on Apple, but it is perfectly fine to parse on Android. But YYY/MM/DD HH: MM: SS works well on both Android and Apple, so we just need to use the same scheme.

const date = "The 2010-12-31 12:30:00";
new Date(date.replace(/\-/g."/"));
Copy the code

Scroll to the specified position

This technique works on both PC and mobile. With the element.scrollintoview () method, we no longer need to use window.scrollby () and window.scrollto () to scrollTo the specified location.

element.scrollIntoView(); // Equates to element.scrollinToView (true) Element.scrollintoView (alignToTop); // Boolean element. ScrollIntoView (scrollIntoViewOptions); // Object parametersCopy the code

AlignToTop Optional, a Boolean value:

  • If true, the top of the element is aligned with the top of the visible area of the scroll area in which it is located. Corresponding scrollIntoViewOptions: {block: “start”, inline: “nearest”} This is the default value for this parameter.

  • If false, the bottom of the element is aligned with the bottom of the visible area of the scroll area in which it is located. Corresponding scrollIntoViewOptions: {block: “end”, inline: “nearest”}

ScrollIntoViewOptions Optional, an object containing the following properties:

  • Behavior Optional, defines the animation transition effect, either “auto” or “smooth”. The default is “auto”.

  • Block optional, define vertical alignment, one of “start”, “Center “, “end”, or “nearest” alignment. The default is “start”.

  • Inline is optional, defines horizontal alignment, one of “start”, “Center “, “end”, or “nearest” alignment. The default is “nearest alignment “.

Landscape and portrait

window.addEventListener("resize".() = >{
    if (window.orientation === 180 || window.orientation === 0) { 
      // Rotate the screen 180 degrees in normal direction
        console.log('portrait');
    };
    if (window.orientation === 90 || window.orientation === -90) {// The screen rotates 90 degrees clockwise or 90 degrees counterclockwise
        console.log('landscape'); }});Copy the code

IPhoneX adaptation

viewport-fit

Viewport-fit is an attribute created specifically for the iPhoneX that restricts how web pages can be displayed in secure areas.

  • Contain: visual window completely contains the content of the web page

  • Cover: The content of the web page completely covers the visual window

The default setting is auto and contain.

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

Env, constant

We need to properly place the top and bottom within the security zone. In iOS11, two new CSS functions, env and constant, are used to set the distance between the security zone and the boundary.

Onstant works on iOS < 11.2, env works on iOS >= 11.2, which means we tend to set them both, limiting pages to safe zones:

There can be four constants inside a function:

  • safe-area-inset-left: Distance between the security zone and the left boundary
  • safe-area-inset-right: Distance between the security zone and the right boundary
  • safe-area-inset-top: Distance between the security zone and the top boundary
  • safe-area-inset-bottom: Distance between the security zone and the bottom boundary

Note: we must specify viweport-fit to use these two functions.

body {
  padding-bottom: constant(safe-area-inset-bottom);
  padding-bottom: env(safe-area-inset-bottom);
}
Copy the code

Dark theme fit scheme

With the release of iOS 13, Dark Mode appears more and more in the public’s view, supporting Dark Mode has become a trend of modern mobile apps and websites, but also caused hot discussion due to the adaptation of wechat some time ago. Dark mode not only dramatically reduces battery consumption, reduces bright light contrast, but also provides better visibility and immersion.

How do I switch to dark mode

  • IOS: Settings -> Display & Brightness -> Appearance -> Select Dark color.
  • Android: System Settings -> Display -> Dark mode.

Adaptation scheme

If the system is set to dark mode, H5 page does not do the corresponding processing, there will be background color conflict, dark text display abnormal, abnormal display of dark ICONS and other display problems.

The statement color scheme


See the color-scheme documentation for details.

Or you can use CSS to get the same effect.

:root {
  color-scheme: light dark;
}
Copy the code

prefers-color-scheme

The PREFERence-color-scheme CSS media feature is used to check whether users set the theme color of the system to bright or dark colors. We can do some special processing by listening for topics that the user has set.

  • no-preference

Indicates that the system is not aware of the user’s options in this regard. In the context of Boolean values, the result is false.

  • light

Indicates that the user has informed the system that they have chosen to use an interface with a light-colored theme.

  • dark

Indicates that the user has informed the system that they have chosen to use an interface with a dark theme.

:root {
    color-scheme: light dark;
    background: white;
    color: black;
}

@media (prefers-color-scheme: dark) {
    :root {
        background: black;
        color: white; }}Copy the code

Processing in JS

In addition to CSS media query can get the user theme, in JS we can also get the user theme.

matchMedia

Window’s matchMedia() method returns a new MediaQueryList object representing the parsed result of the specified media query (en-US) string. The returned MediaQueryList can be used to determine whether a Document matches a media query, or to monitor a Document to determine whether it matches or stops matching the media query.

const mqList = window.matchMedia(mediaQueryString)
Copy the code

addListener()

The addListener() method of the MediaQueryList interface adds a listener to MediaQueryListener that runs a custom callback function in response to changes in the state of the media query.

MediaQueryList.addListener(func) 
Copy the code

You need both in JS

const mediaQuery = window.matchMedia('(prefers-color-scheme: dark)')

function darkModeHandler() {
    if (mediaQuery.matches) {
        console.log('Now in dark mode')}else {
        console.log('Now it's light-colored.')}}// Listen for mode changes
mediaQuery.addListener(darkModeHandler)
Copy the code

Refer to the article

Senior front-end H5 pit must pay attention to article 40 of the mobile end guide | netease three years practice

Here’s what you need to know about mobile adaptation

Mobile Adaptation Solution Guide 2022 – The latest and most complete network

Afterword.

This article is the author’s personal study notes, if there are fallacies, please inform, thank you! If this article helped you, please give it a thumbs up