Essential knowledge for mobile H5 web development

Introduction

If you want to do your job well, you must first sharpen your tools. Today’s article mainly explains some basic knowledge necessary for mobile H5 development, as well as mobile adaptation and layout solutions. If you have already read this article or have mastered the basics of the mobile terminal, you can read the article written by the author.

Summary of Frequently Asked Questions about Mobile H5 Web Page Development

Essential Knowledge for Mobile Development-Hybrid App

pixel

A pixel is a small square that has a specific position and color. Pictures and electronic screens (mobile phones, computers) are spliced ​​by specifying a number of small squares with specific colors and specific positions. For example, our computer screen has a 1920 * 1080 computer screen, and there are 1920 pixels in the horizontal direction and 1080 pixels in the vertical direction.

There are three types of pixel units: device pixel, logical pixel, and CSS pixel.

Device Pixels, Individual Pixels, Device Pixel Ratio, CSS Pixels

Device Pixels

Device pixels are also called physical pixels, which are the smallest display unit on the screen, that is, the real physical unit on the device, which is determined when the device is produced. (iphone6 ​​750px) is generally larger than individual pixels.

independent pixel

Independent pixel (DP or Dip) is a kind of virtual pixel, which is a logical unit to measure pixels, equal to css pixels without scaling. (iphone5 320px iphone6 ​​375px).

device pixel ratio

The device pixel ratio dpr is the ratio of device pixels to individual pixels. For example, the dpr of iphone6 ​​is 2, and the dpr of iphone6 ​​Plus is 3.

In the web, the browser provides us with window.devicePixelRatio to help us obtain dpr. In css, the dpr can be obtained using the media query min-device-pixel-ratio. In React Native, we can also use PixelRatio.get() to get dpr.

@media (-webkit-min-device-pixel-ratio: 2), (min-device-pixel-ratio: 2) {
    
    }

What is the ratio between device pixels and device independent pixels? The general rule is that the higher the pixel density of the screen, the more device pixels are needed to display one device independent pixel.

CSS pixels

The px used in CSS refers to CSS pixels, such as width: 128px. The size of css pixels is easy to change. When we zoom the page, the number of css pixels of the element will not change, but only the size of each css pixel. That is to say, after scaling the element with width: 128px to 200%, its width is still 128 css pixels, but the width and height of each css pixel are doubled. If the original element width is 128 device-independent pixels, then after scaling 200%, the element width is 256 device-independent pixels.

The relationship between css pixels and device-independent pixels

  • The scaling ratio is css pixel side length/device independent pixel side length;
  • In the case of a zoom ratio of 100%, 1 css pixel size is equal to 1 device-independent pixel;
  • At 200% scaling, 1 css pixel size equals (2 * 2) device-independent pixels;

Retina screen

We talked about the pixel to device pixel ratio earlier, and here we talk about the Retina screen. The so- Retinacalled display standard is to compress more pixels into one screen, so as to achieve higher resolution and improve the fineness of the screen display. At a normal reading distance, the human eye cannot distinguish the pixel particles on the screen, making the screen display more delicate and smooth. Starting from iPhone4, Apple has configured screens for its products mac, iPhone, and iPad Retina.

There are different ways to increase the resolution

  • Normal screens increase resolution by increasing in size.
  • The Retina screen increases the resolution by increasing the number of pixels per unit area of ​​the screen (increasing the PPI), that is, the pixel density, so that there is 高像素密度屏幕.

The same device physical size, the conversion of CSS pixels and physical pixels is different

  • Ordinary screen: 1px is equal to one physical pixel.
  • Retina screen: 1px is equal to four physical pixels.

k and p

We often see the unit of K and P to describe the screen:

  • P represents the number of pixels in the vertical direction of the screen, 1080P means that there are 1080 pixels in the vertical direction, and a screen with a resolution of 1920X1080 is a 1080P screen.
  • K represents how many pixels there are in the horizontal direction of the screen. Generally speaking, if the horizontal pixels exceed 2048, it belongs to a 2K screen, and if the horizontal pixels exceed 4096, it belongs to a 4K screen.

inch

Generally, inches are used to describe the physical size of the screen, such as 17, 22 for computer monitors, 4.8, 5.7 for mobile phone monitors, etc., all use inches. It should be noted that the size is the length of the diagonal of the screen. 1 inch = 2.54 centimeters.

PPI

PPI (Pixel Per Inch): The number of pixels per inch.

PPI can be used to describe the sharpness of a screen and the quality of a picture. When using PPI to describe pictures, the higher the PPI, the higher the picture quality; when using PPI to describe the screen, the higher the PPI, the clearer the screen.

Calculation method The square root of the sum of the square of the horizontal pixel count and the square of the vertical pixel count is divided by the screen inch (screen diagonal length).

DPI

DPI (Dot Per Inch): That is, the number of dots per inch.

Usually, you may see that DPI is used to describe pictures and screens. At this time, DPI should be equivalent to PPI. DPI is most commonly used to describe printers, indicating the number of dots a printer can print per inch.

Therefore, the higher the DPI of the printer, the higher the fineness of the printed image, and at the same time, it will consume more ink dots and time.

em

em Relative to the element itself font-size, 1em is equal to font-sizethe size of the element. Due to font-sizeinheritance, even if font-sizethe size of this element is not set, it will inherit the parent element font-size. If there is no parent element, it will search up the DOM tree until the root element html. The default font size of the root element is 16px.

rem

With the basis of em, rem is even simpler. rem is only font-sizerelated to the size of the root element html, and the size is fixed. 1 remis equal to the font size htmlof .

viewport

layout viewport

Layout viewport, when displaying a webpage on the mobile terminal, because the screen size of the mobile terminal is relatively small, if the webpage is laid out using the screen size of the mobile terminal, the layout of the entire page will be displayed in disorder. Therefore, mobile browsers provide a concept of layout viewport, which is used to display the layout of the page. Generally, the default size of layout viewport is 980px, which ensures that PC web pages can be rendered on mobile browsers, but Very small, users can manually zoom in on the webpage. We can get the layout viewport size by calling document.documentElement.clientWidth / clientHeight. The layout viewport can be understood as the width of your web page.

visual viewport

Visual viewport, visual viewport refers to the viewport size of the area we can see on the mobile device, generally the independent pixel size of the device. The relationship between visual viewport and layout viewport is like we look at the outside scenery through the window, the visual viewport is the window, and the outside scenery is the webpage content in the layout viewport. We can get the visual viewport size by calling window.innerWidth / innerHeight. The visual viewport can be understood as the device-independent pixel size.

ideal viewport

Ideal viewport, since the layout viewport is generally larger than the visual viewport, you must drag and zoom to see the entire page. Therefore, the concept of ideal viewport is proposed. Under ideal viewport, users can view the entire page without zooming and scrolling, and the content displayed on the page at different resolutions is the same size. The ideal viewport actually modifies the size of the layout viewport to make it equal to the width of the device. This width can be understood as an independent pixel of the device. Therefore, the pages designed according to the ideal viewport should display the same under different resolution screens. We can get the ideal viewport size by calling screen.width / height, which returns device-independent pixels. The ideal viewport can be understood as the equal layout viewport and visual viewport.

Use meta tags to control viewport

The default viewport of mobile devices is the layout viewport, which is the viewport wider than the screen, and the default width is 980px. Therefore, we often use meta tags to control the viewport. Generally, we set width=device-widththe layout viewport and the visual viewport to be equal to achieve the ideal viewport.

<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no" />

properties of the viewport

  • width positive integer or device-width in pixels (pixels), defines the width of the layout viewport.
  • height positive integer or device-height in pixels (pixels), defines the height of the layout viewport.
  • initial-scale0.0 - 10.0 defines the initial zoom ratio of the page.
  • minimum-scale0.0 - 10.0 Defines the minimum value for scaling; must be less than or equal to the value of maximum-scale.
  • maximum-scale0.0 - 10.0 Defines the maximum value for scaling; must be greater than or equal to the value of minimum-scale.
  • user-scalable A boolean value (yes or no). If set to no, the user will not be able to zoom in or out on the page. The default value is yes

Adaptation scheme

There are all kinds of mobile phones and mobile phone screens, so when doing mobile H5 development, you must understand the adaptation scheme. That is, our set of codes is compatible with various types of mobile phones. The mobile terminal adaptation schemes mainly include @media媒体查询方案, rem方案, vw vh方案, and we will introduce them one by one below.

Media query @media using css

Use media queries to adapt to different screens. If you are interested in media queries, you can learn by yourself.

@media *mediatype* and|not|only *(media feature)*  {
    
    
    CSS-Code;
}
@media screen and (min-width: 375px) {
    
     .box {
    
     width : 160px; } }

@media screen and (min-width: 750px) {
    
     .box {
    
     width : 320px; } }

Although media queries can solve the adaptation problem, the disadvantages of using media queries are also obvious

  1. All elements on the page have to define different sizes in different @media, and the code is redundant.
  2. If there is one more screen size, one more @media query block needs to be written.
  3. The writing order of the media query blocks is also very particular, and the later ones will overwrite the previous ones, which is easy to make mistakes.

use rem

We have already introduced rem before, and the size of 1rem is font-sizethe size of the html element. So the core of using rem layout is to dynamically set htmlthe font size of the root element. lib-flexibleAmong the rem adaptation schemes, the Amoy and schemes are more popular amfe-flexible.

lib-flexibleAnd amfe-flexiblethese two mobile terminal adaptation solutions are based on rem. Let's introduce the usage method in detail below, but the official document also said that because viewportthe unit is compatible with many browsers, lib-flexibleand amfe-flexiblethis transitional solution can already be abandoned, whether it is the current version or the previous version, there are certain problems. It is recommended that you start using it viewportinstead of this one.

lib-flexible

Those who are interested can look at the source code of lib-flexible , this version will be automatically generated viewport meta标签.

Core code:

// 根元素字体的大小是布局视口大小/10。
function refreshRem(){
    
    
  var width = docEl.getBoundingClientRect().width;
  if (width / dpr > 540) {
    
    
      width = 540 * dpr;
  }
  var rem = width / 10;
  docEl.style.fontSize = rem + 'px';
  flexible.rem = win.rem = rem;
}
// 动态生成 viewport meta标签
if (!metaEl) {
    
    
  metaEl = doc.createElement('meta');
  metaEl.setAttribute('name', 'viewport');
  metaEl.setAttribute('content', 'initial-scale=' + scale + ', maximum-scale=' + scale + ', minimum-scale=' + scale + ', user-scalable=no');
  if (docEl.firstElementChild) {
    
    
      docEl.firstElementChild.appendChild(metaEl);
  } else {
    
    
      var wrap = doc.createElement('div');
      wrap.appendChild(metaEl);
      doc.write(wrap.innerHTML);
  }
}

important point:

// 如果是苹果手机,才会根据dpr进行缩放,其余的都不做缩放处理
// 我觉得这里的设计应该主要是解决1px的问题吧,在amfe-flexible方案中已经放弃了
if (!dpr && !scale) {
    
    
  var isAndroid = win.navigator.appVersion.match(/android/gi);
  var isIPhone = win.navigator.appVersion.match(/iphone/gi);
  var devicePixelRatio = win.devicePixelRatio;
  if (isIPhone) {
    
    
      // iOS下,对于2和3的屏,用2倍的方案,其余的用1倍方案
      if (devicePixelRatio >= 3 && (!dpr || dpr >= 3)) {
    
                    
          dpr = 3;
      } else if (devicePixelRatio >= 2 && (!dpr || dpr >= 2)){
    
    
          dpr = 2;
      } else {
    
    
          dpr = 1;
      }
  } else {
    
    
      // 其他设备下,仍旧使用1倍的方案
      dpr = 1;
  }
  scale = 1 / dpr;
}

How to use lib-flexible:

// 安装
npm install lib-flexible --save-dev

// 引用
import 'lib-flexible/flexible.js'

This will automatically generate our index.html page viewport meta标签, such as<meta name="viewport" content="initial-scale=0.5, maximum-scale=0.5, minimum-scale=0.5, user-scalable=no">

With lib-flexiblethe appropriate configuration, it can be adapted to different mobile phone screens. We just need to remember the calculation formula 某元素css尺寸 = 某元素设计稿尺寸/(设计稿宽度/10). For example, the design draft of the designer is 375, assuming that the height of an element on the design draft is 75px, we need to set the height of the element in the code to 75/(375/10) = 2rem.

If you feel that manual calculation is particularly tiring, we can use the postcss-pxtorem plug-in to automatically calculate it for us.

The core of the postcss-pxtorem plugin is that we need to set rootValue. If our design draft is 375, we only need to set rootValue to 37.5. If our design draft is 750, we only need to set rootValue to 75. In this way, we only need to set the px size for the element according to the design in css, and the plug-in will automatically calculate the value of rem for us when packaging, isn’t it great?

// 这里是postcss-pxtorem插件的默认配置
{
    
    
  rootValue: 16,
  unitPrecision: 5,
  propList: ['font', 'font-size', 'line-height', 'letter-spacing'],
  selectorBlackList: [],
  replace: true,
  mediaQuery: false,
  minPixelValue: 0,
  exclude: /node_modules/i
}

// 一般我们只需要修改rootValue即可
{
    
    
  rootValue: 37.5,
}

amfe-flexible

Those who are interested can look at the source code of amfe-flexible . This version of the code is more concise and is not automatically generated viewport meta标签.

Core code:

// set 1rem = viewWidth / 10
function setRemUnit () {
    
    
  var rem = docEl.clientWidth / 10
  docEl.style.fontSize = rem + 'px'
}

How to use:

// 安装
npm install amfe-flexible --save-dev

// 引用
import 'amfe-flexible/index.js'

// 在index.html页面添加  viewport meta标签
<meta name="viewport" content="width=device-width, initial-scale=1.0,maximum-scale=1.0, minimum-scale=1.0, user-scalable=no">

In amfe-flexiblethe scheme, there is no dpr, no automatic viewport metalabel generation, no page zoom, and it becomes more concise.

lib-flexibleSimilar to the way of use, with amfe-flexibleproper configuration, it can be adapted to different mobile phone screens. We just need to remember the calculation formula 某元素css尺寸 = 某元素设计稿尺寸/(设计稿宽度/10). For example, the design draft of the designer is 375, assuming that the height of an element on the design draft is 75px, we need to set the height of the element in the code to 75/(375/10) = 2rem.

If you feel that manual calculation is particularly tiring, we can use the postcss-pxtorem plug-in to automatically calculate it for us.

The core of the postcss-pxtorem plugin is that we need to set rootValue. If our design draft is 375, we only need to set rootValue to 37.5. If our design draft is 750, we only need to set rootValue to 75. In this way, we only need to set the px size for the element according to the design draft in css, and the plug-in will automatically calculate the value of rem for us when packaging, isn’t it great?

// 这里是postcss-pxtorem插件的默认配置
{
    
    
  rootValue: 16,
  unitPrecision: 5,
  propList: ['font', 'font-size', 'line-height', 'letter-spacing'],
  selectorBlackList: [],
  replace: true,
  mediaQuery: false,
  minPixelValue: 0,
  exclude: /node_modules/i
}

// 一般我们只需要修改rootValue即可
{
    
    
  rootValue: 37.5,
}

use vw vh

[External link picture transfer failed, the source site may have an anti-leeching mechanism, it is recommended to save the picture and upload it directly (img-MMIMb2P3-1668602484737)(https://p1-juejin.byteimg.com/tos-cn-i-k3u1fbpfcp /7a8115dc49f94892964ae1913e4818ec~tplv-k3u1fbpfcp-watermark.image?)]

  • vw: shorthand for viewport's width, screen width = 100vw.
  • vh: Similar to vw, it is short for viewport's height, screen height=100v.
  • vmin: The value of vmin is the smaller value of the current vw and vh.
  • vmax: The value of vmax is the larger value among the current vw and vh.

The adaptation method using vw and vh is simpler than the rem method. We only need to set the viewport meta tag and then use it directly.

How to use:

// 在index.html页面添加  viewport meta标签
<meta name="viewport" content="width=device-width, initial-scale=1.0,maximum-scale=1.0, minimum-scale=1.0, user-scalable=no" />

Similar to the above lib-flexibleand amfe-flexibleusage, so that it can be adapted to different mobile phone screens. We just need to remember the calculation formula 某元素css尺寸 = 某元素设计稿尺寸/(设计稿宽度/100) vw. For example, the design draft of the designer is 375, assuming that the height of an element on the design draft is 75px, we need to set the height of the element in the code to 75/(375/100) = 20vw. It should be noted here that we can only use vw as the unit for width and height.

If manual calculation is particularly tiring, we can use the postcss-px-to-viewport plug-in to automatically calculate it for us.

The core of the postcss-px-to-viewport plugin is that we need to set viewportWidththe width of the design draft (this is the difference from postcss-pxtorem), if our design draft is 375, we only need to set it viewportWidthto 375, if our The design draft is 750, we only need to set it viewportWidthto 750. In this way, we only need to set the px size for the element according to the design draft in css, and the plug-in will automatically calculate the value of vw for us when packaging, isn’t it great?

// 这里是postcss-px-to-viewport插件的默认配置
{
    
    
  unitToConvert: 'px',
  viewportWidth: 320,
  unitPrecision: 5,
  propList: ['*'],
  viewportUnit: 'vw',
  fontViewportUnit: 'vw',
  selectorBlackList: [],
  minPixelValue: 1,
  mediaQuery: false,
  replace: true,
  exclude: undefined,
  include: undefined,
  landscape: false,
  landscapeUnit: 'vw',
  landscapeWidth: 568
}
// 一般我们只需要改viewportWidth即可
{
    
    
  viewportWidth: 375,
}

We can also use the Ignoring feature of the postcss-px-to-viewport plugin to mark properties that do not need to be converted

  • /* px-to-viewport-ignore */ The current line is not converted
  • /* px-to-viewport-ignore-next */ The next line does not convert
.box {
    
    
  /* px-to-viewport-ignore-next */
  width: 10px;
  height: 10px;
  padding: 10px; /* px-to-viewport-ignore */
}

layout scheme

After talking about the adaptation of the mobile terminal, let’s talk about the layout scheme of the mobile . No more details.

Among so many layouts, the author thinks that we must master flexlayout and gridlayout, because in daily H5 development, these two layouts are basically inseparable. There are a lot of tutorials about flex布局and grid布局, here I won't teach you how to do it, I recommend everyone to read Mr. Ruan Yifeng's Flex layout tutorial and Grid grid layout tutorial . After mastering these two sets of mental methods, I think there is nothing difficult for you in terms of mobile H5 development layout.

expand

Common APIs about window size

screen.width 获取屏幕的宽度 跟浏览器无关
screen.height 获取屏幕的高度 跟浏览器无关
screen.availWidth 获取屏幕有效宽度 如果任务栏设置在左右两侧的话,去除任务栏宽度
screen.availHeight 获取屏幕有效高度 去除任务栏高度

window.outerWidth 获取浏览器宽度 包括浏览器所有包括侧边栏、窗口镶边和调正窗口大小的边框。
window.outerHeight 获取浏览器高度 包括浏览器所有包括侧边栏、窗口镶边和调正窗口大小的边框。
window.innerWidth:获取浏览器视觉视口宽度(包括滚动条)。
window.innerHeight:获取浏览器视觉视口高度(包括滚动条)。
document.documentElement.clientWidth:获取浏览器布局视口宽度。不包括滚动条。
document.documentElement.clientHeight:获取浏览器布局视口高度。不包括滚动条。

dom.clientWidth:获取元素的宽度 包括内容和内边距
dom.clientHeight:获取元素的高度 包括内容和内边距
dom.offsetWidth:获取元素的宽度 包括内容、内边距、滚动条、边框。
dom.offsetHeight:获取元素的高度 包括内容、内边距、滚动条、边框。
dom.scrollWidth:获取元素内容实际的宽度 包括内边距。
dom.scrollHeight:获取元素内容实际的高度 包括内边距。

dom.clientTop:获取元素上边框高度
dom.clientLeft:获取元素左边框宽度
dom.offsetTop:获取元素距离页面顶部高度
dom.offsetLeft:获取元素距离页面左边的宽度
dom.scrollTop:获取元素滚动条在垂直方向上滚动的距离
dom.scrollLeft:获取元素滚动条在水平方向上滚动的距离

postscript

This article is the author's personal study notes, if there is any fallacy, please let me know, thank you very much! If this article is helpful to you, please like it~~

Guess you like

Origin blog.csdn.net/weixin_38664300/article/details/127892903