1. Introduction

1.1 parameters of IPhone6

Device pixel 750 * 1334

Device independent pixel 375 * 667

Screen resolution 750 x 1334

ppi 326

Generally set the maximum and minimum width of the mobile terminal

min-width:320px;
max-width:640px;
Copy the code

1.2 980 Layout of visual ports

980 pixels is the initial width of the layout viewport set by the browser manufacturer

1.3 Methods of data sharing

  1. Increase the scope of variables.
  2. Store data in an object

1.4 addEventListener Is the third parameter

document.documentElement.addEventListener('touchstart'.function(e){
    // Prevent default behaviore.preventDefault(); }, {passive:false // Passive mode True false Controls whether E. preventDefault is invalid
}); 
Copy the code

2. Screen relevance

2.1 Screen Size

Screen size refers to the diagonal length of a screen, usually in inches. Common mobile phone screen size 3.5, 4, 4.7, 5.0, 5.5, 6.0 and so on. Common mobile screens check out the url screensiz.es/

Note:

  • The foot is 4.7inch. The foot is 4.7inch

  • 1 foot = 12 inch 1 inch = 2.54 cm

2.2 Screen Resolution

Screen resolution refers to the number of pixels on a screen vertically and horizontally. The general notation is x times y or y times x. For example, the IPhone 6 has a screen resolution of 750 x 1334, and the Huawei P30 has a screen resolution of 2340 x 1080.

Note:

  • Screen resolution is a fixed value, and it’s fixed when it’s produced, whether it’s a phone screen or a computer screen.
  • Screen resolution is different from display resolution. The computer can modify the display resolution, the signal is transmitted to the screen, the screen will be calculated, displayed on the screen.
  • The 1080P resolution is 1920×1080 720P 1280 x720
  • A 2K screen is a display device with a single-direction resolution of about 2000 pixels. The most standard 2K resolution is 2048×1024

The resolution of several phones

model The resolution of the
IPhone 3GS 320 * 480
IPhone 4 / 4s 640 * 960
IPhone 5 / 5s 640 * 1136
IPhone 6 / 7 / 8 750 * 1334
Huawei P30 1080 * 2340
IPhone X 1125 * 2436

4. The viewport viewport

4.1 PC

On the PC side, viewport refers to the viewable area of the browser. The width is the same as the width of the browser window. In the CSS standard documentation, viewports are also referred to as initial inclusion blocks, which are the root of all CSS percentage width calculations.

// Get the width of the viewable area without the scroll bar
document.documentElement.clientWidth

// Gets the width of the browser window containing the scroll bar
window.innerWidth

// Get the total width of the browser including the outer shadow
window.outerWidth

Screen The total width of the screen
screen.width
Copy the code

4.2 the mobile end

The viewport on the mobile terminal is different from that on the PC, with three viewports

  • Layout viewport
  • Visual viewport
  • Ideal viewport

4.2.1 Layout viewport: the area for placing web content

Layout viewports are areas where web content is placed.

By default, browsers on mobile devices define a virtual layout viewport to solve the problem of early page display on mobile phones. The viewport size is determined by the browser vendor. If viewport is not set, most devices have a layout viewport size of 980px.

Obtaining method:

document.documentElement.clientWidth // Layout viewport width
document.documentElement.clientHeight
Copy the code

4.2.2 Visual port: the area visible to the user

The visual viewport is the area visible to the user: window.innerWidth

access

window.innerWidth // The width of the visual port
window.innerHeight
Copy the code

Note: Visual viewport width == layout viewport width without scaling.

4.2.3 Ideal viewport

A layout viewport that is as wide as the screen is called an ideal viewport. Benefits of an ideal viewport

  • Users can see the entire site without zooming or scrollbars.
  • Designs for mobile are easier to develop.

Note: Ideal viewports are not real viewports

How to set up the ideal viewport

<meta name="viewport" content="width=device-width" />< - or - ><meta name="viewport" content="Initial - scale = 1.0" /><-- fit (recommended)--><meta name="viewport" content="Width = device - width, initial - scale = 1.0" />

Copy the code

4.2.4 Common Parameters

// Get the layout viewport width
console.log(document.documentElement.clientWidth);

// Get the width of the visual viewport
console.log(window.innerWidth);
Copy the code

5. The zoom

5.1 PC

Zoom in

  • Layout viewports become smaller
  • The visual viewport becomes smaller
  • The pixel size of the element remains the same

Zoom out

  • Layout viewports become larger
  • The visual viewport becomes larger
  • The pixel size of the element remains the same

5.2 the mobile end

Zoom in

  • The layout viewport remains unchanged
  • The visual viewport becomes smaller

Zoom out

  • The layout viewport remains unchanged
  • The visual viewport becomes larger

Note: mobile zooming does not affect page layout

6. Real machine test process

Real machine testing is a necessary process of project testing, must master!!

  1. Disabling the Firewall

  2. Webstorm -> CTRL + Alt + S -> Search for debugger -> Modify port and select two multi-check boxes. 8000 8888 is recommended if the port is larger than 1024

  3. Make PC and mobile phone in the same network. It is most convenient to connect your phone to your computer’s wifi, or your computer to your phone’s hotspot, both under the same wifi.

  4. CMD query the IP address of the wireless network card (ipconfig)

  5. Webstorm previews the file in the browser and changes localhost to IP

  6. Open the forage website cli.im/ convert the URL into a two-dimensional code, which can be scanned by mobile phone 😎

7. The viewport control

The ViewPort TAB was introduced by Apple in 2007 for the control of mobile layout viewports.

Use the sample

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

Viewport-related options

  • Width Width of the layout viewport
  • Initial-scale Initializes the scaling scale
  • Minimum-scale Specifies the minimum scale
  • Maximum-scale Indicates the maximum scaling ratio
  • User-scalable setting whether to allow users to scale
  • viewport-fit auto/contain/cover

width

The width value can be either a number or a device width to indicate device-width to get a perfect viewport

initial-scale

Initial-scale indicates the display scale when the page is initialized.

Scale = screen width single pixel/layout viewport width. / / iphone6 0.5

Note:

  • Chrome test this parameter will be biased, real machine test
  • Initial-scale = 1.0 also yields a perfect viewport
  • Initial-scale affects the size of layout viewports and visual viewports
  • If width and initial-scale are set at the same time, the larger size is selected

minimum-scale

Set to allow the user the minimum zoom scale.

Minimum-scale = Screen independent pixel width/visual port // iPhone 6 0.5

maximum-scale

Sets the maximum zoom ratio allowed to the user. Safari does not recognize this property

Maximum-scale = screen independent pixel width/visual port // 2

user-scalable

Whether to allow users to zoom in and out of the page with their fingers. Safari, Apple’s browser, does not recognize this property.

viewport-fit

If the value is set to Cover, the “fringe screen” is left blank

8. Mobile events

8.1 Event Types

List of events on the mobile end

  • Triggered when a touch starts on the touchStart element
  • Triggered when a touch moves on the TouchMove element
  • Touchend is triggered when the finger is removed from the element
  • Touchcancel Is triggered when a touch is interrupted

These events first appeared in IOS Safari to convey some special information to developers

Other common events:

Keyboard:

onkeydown onkeypress onkeyup

Roller:

onmousewheel

Documents:

onload onbeforeunload

<script type="text/javascript">
    // Determine if the user has left your page
    window.onbeforeunload=function () {
    return Are you sure you want to leave? ';
}
</script>
Copy the code

Form:

onfocus onblur onsubmit onreset

Mouse:

onclick onmouseenter onmouseleave onmouseover onmouseout onmousedown onmousemove onmouseup

8.7 IOS Multiple Events

The event type

  • Gesturestart: Finger touches the current element. There are two or more fingers on the screen
  • Gesturechange: Two or more finger positions on the screen move when a finger touches the current element
  • Gestureend: After gesturestart, less than two fingers (excluding two) are left on the screen

Many refer to event attributes

  • Rotation: Indicates the rotation Angle caused by finger changes. A negative value means counterclockwise rotation, and a positive value means clockwise rotation.
  • Scale: indicates the change in the distance between two fingers (e.g. shrinking inward shortens the distance); This value starts at 1 and increases with distance and decreases with distance. According to our physiological limits, negative values are not allowed

8.2 Application Scenarios

The TouchStart event can be used for element touch interactions, such as page jumps and TAB switches

The TouchMove event can be used for sliding effects on pages, web games, and artboards

The TouchEnd event is used primarily in conjunction with the TouchMove event

Touchcancel usage is not high

Note:

  • After the TouchMove event is triggered, the TouchMove event will continue to fire even if the finger leaves the element
  • To trigger the TouchMove and TouchEnd events, you must first trigger touchStart
  • The function of events is to achieve mobile interface interaction

8.3 Event Binding

A:

box.ontouchstart = function(){
    console.log('touch start')}Copy the code

Method 2 (Recommended) :

box.addEventListener('touchstart'.function(){
	console.log('touch start')})Copy the code

8.4 Click Through

After the touch event ends, the click event of the element will be triggered by default. If the perfect viewport is not set, the event will trigger the time interval of about 350ms, if the perfect viewport is set, the time interval of about 5ms.

If the touch event hides an element, the click action is applied to the new element, triggering a click event or page jump for the new element, a phenomenon known as clickthrough

 var t1 = 0;
  var box = document.getElementById('box');
  box.addEventListener('touchstart'.function () {
    console.log('Triggered the TouchStart event');
    t1 = Date.now(); // Get the timestamp of the current time
  });
  box.addEventListener('click'.function () {
    console.log('Triggered the click event');
    var t2 =Date.now();
    console.log('Time interval:', t2 - t1); 
  })
Copy the code

The solution

Method 1: Block the default behavior of the current element event.

cls.addEventListener('touchstart'.function(e){ e.preventDefault(); })// Right mouse button does not play custom menu
window.oncontextmenu=function (e) {
   e.preventDefault();
 }
Copy the code

Method 2: Prevent the default behavior of top-level element events by adding a wrap element binding or binding document and window, but turn off passive mode

 document.addEventListener('touchstart'.function (e) {
    e.preventDefault();
  }, {passive: false});
Copy the code

Method 3: Replace the A tag with a non-linked element, set the link address attribute, and bind the TouchStart event

<div class="item">
  <div data-href="http://m.atguigu.com">
    <img src="holder.js/60x60? bg=#a76">
  </div>
     <div data-href="http://m.atguigu.com">
    <img src="holder.js/60x60? bg=#a76">
  </div>
     <div data-href="http://m.atguigu.com">
    <img src="holder.js/60x60? bg=#a76">
  </div>
</div>Use the TouchStart event to get the data-href attribute and adjust the link location.href=XXX;Copy the code

Method 4: Delay hiding mask layer elements

  setTimeout(function () {
    el.style.display = 'none';
  }, 400);
Copy the code

8.5 Page forward selection

Mobile terminal page jump can use a link, or use touchStart event to trigger JS code to complete the jump

  • In terms of efficiency, TouchStart is faster
  • SEO optimization, a link effect is better

8.6 Default browser behavior (generally do not need to block)

There are three main browser defaults

  • Sliding down reveals blank space
  • A long press displays menu actions such as copy and copy
  • Page zoom

8.6.1 Why do I block these default behaviors

This allows web pages to behave the same in different browsers.

8.6.2 How do I Prevent the Default Behavior

You can bind the Document to the TouchStart event and prevent the default behavior, but you need to turn off passive mode. It is recommended to create a wrap element that binds the TouchStart event and prevents the default behavior.

CSS code

html.body.#app {   
    width: 100%;    
    height:100%;  
    overflow: hidden;
}
Copy the code

The HTML code

<body>
	<div id="app">
        XXXXXX
    </div>
</body>
Copy the code

JS code

var app=document.documentGetElementById('app')App.addeventlistener (' touchStart ', function (e) {e.preventDefault(); })
Copy the code

8.6.3 sequela

After the outermost element blocks the touchStart default behavior, something unexpected happens 😭

  • A link failure
  • Contents cannot be selected
  • The form element cannot get focus

8.6.4 Final Solution: Prevent bubble propagation ()

The reason for the “hangover” is that TouchStart blocks the default behavior and all subsequent actions are no longer valid.

Fix the problem: Just bind the TouchStart event to the target element and prevent the event from bubbling, so the default behavior of the current operation is still available.

var link = document.getElementsByTagName('a') [0]; // Target element
link.addEventListener('touchstart'.function (e) {
    e.stopPropagation(); // Prevent events from bubbling
})
Copy the code

Note: it is not necessary to prevent the default behavior of the browser, this is an extreme request to cope with the normal need to set up a perfect viewport.

<! doctypehtml>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport"
          content="Width =device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
    <style>
        * {
            margin: 0;
            padding: 0;
        }
 
        ul {
            list-style: none;
        }
 
        #box {
            width: 100%;
            height: 2000px;
            background: linear-gradient(to bottom, #98a.#aef);
        }
    </style>
</head>
<body>
<div id="app">
    <div id="box">
        <h2><a href="http://www.baidu.com/s?wd= Instant Noodles">Lanting preface</a></h2>
        <div>The author:<input type="text"></div>
        <p>Yonghe nine years, at the age of Guichou, at the beginning of late spring, would go for an outing at the Lanting, shanyin Kuiji. Gather the sage together, and grow the salt less. Here there are mountains, forests and bamboo, and there is a clear current exciting turbulence, around the projection belt, led to think that the sandy-lovee water, row sit next. Although there is no silk and bamboo orchestra sheng, a crystal, also enough to Syria. The sun is also, the sky is clear, the wind is smooth. Looking up to the universe of the big, look at the sheng of the categories, so the view is free, enough to entertain the hearing and hearing, the letter also coke. The lady with, bow a world. Or take the embrace and realize the words in one room; Or because of the trust, loose beyond. Although the interest is different and the restlessness is different, when it is happy in the encounter, it temporarily obtains from itself, and quickly becomes self-sufficient, not knowing that old age is coming. I am tired of feeling sorry for myself. To the xin, between the bow, has been a relic, still can not not with the xing Huai, the situation is short with the end of the end! The ancients said, "Death and life are also great." It doesn't hurt! Every glance past people xing feeling by, if the unity of the deed, not not in the text of mourning, can not be yu Huai. Solid know dead life for vain, Qi Peng shang for vain. After the sight of today, but also today of the past, sad husband! Therefore, the people of the time, recorded its description, although the world is different things, so xing Huai, its cause one also. After the tour, will also feel sven.</p>
    </div>
</div>
<script>
    var app = document.querySelector('#app');
    var p = document.querySelector('p');
    var input = document.querySelector('input');
 
    // Block the browser's default behavior
    app.addEventListener('touchstart'.function (e) {
        e.preventDefault();
    });
 
    // Get the a link
    var a = document.querySelector('a');
 
    a.addEventListener('touchstart'.function (e) {
        // Prevent bubbling
        e.stopPropagation();
    });
 
    // Stop m bubbling, long press the text to copy
    p.addEventListener('touchstart'.function(e){
        e.stopPropagation();
    });
   // input gets focus
    input.addEventListener('touchstart'.function(e){
        this.focus();
        e.stopPropagation();
    });
  // Input loses focus
    app.addEventListener('touchstart'.function(){
       input.blur();
    });
 
</script>
</body>
</html>
Copy the code

9. Event object properties

There are three very important properties in the Touch event object

  • changedTouches
  • targetTouches
  • touches
  • Gets the position of the finger as it leaves the element: Only changedTouches can be used

9.1 touchstart event

In the TouchStart event,

ChangedTouches is an array of touch objects that are currently pressed simultaneously on the element.

TargetTouches is an array of touch objects on the current element after being pressed

Touches is an array of all touch objects on the current screen after the touch is pressed

9.2 touchmove events

In the TouchMove event

ChangedTouches is an array of touch objects that are currently sliding on elements at the same time.

TargetTouches is an array of touch objects on the current element when sliding

Touches is an array of all touch objects on the current screen when sliding

9.3 touchend events

In the TouchEnd event

ChangedTouches is an array of touch objects currently lifted at the same time on the element.

TargetTouches for the end of the touch object array on the current element

Touches ends with an array of all touch objects on the current screen

9.4 Contact objects

Each touchpoint object contains some location information, including

  • The offset of clientX relative to the left of the viewable area
  • The offset of the clientY relative to the top side of the visible area
  • PageX offset relative to the left side of the document
  • The offset of pageY relative to the top of the document

Case 1: Get the coordinates of the current mouse click

var box = document.querySelector('#box'); Box-click = function(e){var x = e.clientx; var y = e.clientY; var a = e.pageX; var b = e.pageY; console.log(x,y, a, b); }Copy the code

Case 2: Obtain information about the current key

// Get the current key information CTRL + C
window.onkeydown = function(e){
    console.log(e.keyCode); // 67 c
    console.log(e);
    if(e.keyCode == 67 && e.ctrlKey){
        // alert(' You pressed CTRL + C ')
        // Prevent users from copying page contente.preventDefault(); }}Copy the code

Case 3: Block right-click pop-up menus

window.oncontextmenu = function(e){
    e.preventDefault();
}
Copy the code

Case 4: Click a single position to obtain the position information of the touch; You can also obtain the position information of the contact by moving the mouse

	// Click a single position to get the position information of the touch; You can also obtain the position information of the contact by moving the mouse
			var box = document.querySelector('#box');
			box.addEventListener('touchstart'.function(e) {
				// Get the contact information
				var x = e.changedTouches[0].clientX;
				var y = e.changedTouches[0].clientY;
				box.innerHTML = 'X:' + x + ' <br> Y:' + y;
			});

			box.addEventListener('touchmove'.function(e) {
				// Get the contact information
				var x = e.changedTouches[0].clientX;
				var y = e.changedTouches[0].clientY;
				box.innerHTML = 'X:' + x + ' <br> Y:' + y;
			});
			// Prevent default behavior
			document.documentElement.addEventListener('touchstart'.function(e) {
				e.preventDefault();
			}, {
				passive: false
			})
Copy the code

Case 5: Drag: Position 4 =3- (1-2)

<! doctype html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, User - scalable = no, initial - scale = 1.0, the maximum - scale = 1.0, Minimum scale=1.0"> <meta http-equiv=" x-UA-compatible "content="ie=edge"> <title>Document</title> <style> * {margin: 0; padding: 0; } ul { list-style: none; } #box { width: 100px; height: 100px; background: darkred; color: white; position: absolute; left: 0; top: 0; / * background: RGB (200241200); </style> </head> <body> <div id="box"> </div> <script> Function (e) {this.size_client_x1 = e.touches[0].clientx; this.size_client_y1 = e.touches[0].clientY; This.size_offset_left1 = box. OffsetLeft; this.size_offset_top1 = box.offsetTop; }); Function (e) {this.size_client_x2 = e.touches[0].clientx; this.size_client_y2 = e.touches[0].clientY; This.size_offset_left2 = box. OffsetLeft; this.size_offset_left2 = box. this.size_offset_top2 = box.offsetTop; var left_val = this.size_client_x2 - (this.size_client_x1 - this.size_offset_left1); var top_val = this.size_client_y2 - (this.size_client_y1 - this.size_offset_top1); / / get the biggest left the value of the var maxLeft = document. The documentElement. ClientWidth - box. OffsetWidth; If (left_val <= 0) {left_val = 0; } if (left_val >= maxLeft) { left_val = maxLeft; } if (top_val <= 0) { top_val = 0; } // set the left top of box to box.style.left = left_val + 'px'; box.style.top = top_val + 'px'; }); document.body.addEventListener('touchstart', function(e) { e.preventDefault(); }, { passive: false }); </script> </body> </html>Copy the code

10. Adaptation

Mobile devices have various screen sizes. In order to make the page display uniform, it is necessary to adapt to devices of different sizes. There are two main ways of adaptation

  • Viewport adaptation
  • Rem adaptation

10.1 the viewport adaptation

After getting the design draft, set the layout viewport width as the width of the design draft, and then measure the size of the layout.

  1. Set viewPort Width equal to the width of the design
  2. Measure the size of the element, and write whatever you measure. For example, if the element is 100 pixels wide, the CSS style is width: 100px

10.2 rem adaptation

www.bilibili.com/video/BV1nV… Refer to the video

Em and REM are both length units in the CSS. And they’re both units of relative length, but they’re a little bit different

  • Em is relative to the font size of the parent element

    <div id="outer"> <div id="inner"> </div> </div> <style> #outer{font-size:40px; } #inner{// 1em=40px } </style>Copy the code
  • Rem is the font size of the root element (HTML)

    <div id="outer"> <div id="inner"> </div> </div> <style> HTML {font-size:80px; } #outer{ font-size:40px; } #inner{// 1rem=80px } </style>Copy the code
  • The core is proportional scaling

There are several strategies for REM adaptation

Method one:

First follow the IPhone 6 page layout, and then adapt

  1. Perfect viewport setup
<meta name="viewport"
              content="Width =device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
Copy the code
  1. The total width of the design draft is 375 layout

    Designs are usually 750*1334 in scale, so the actual CSS element size is equal to the measured width /2

  2. Font size = 100px for IPhone 6 root element

  3. Add JS code for automatic HTML font size Settings

// Use the IPhone 6 root element font size=100px as a reference to calculate the root element font size for any device
document.documentElement.style.fontSize = document.documentElement.clientWidth*100/375+'px';
 
    window.onresize = function () {
        document.documentElement.style.fontSize = document.documentElement.clientWidth*100/375+'px';
    }
Copy the code
  1. Calculate the rem

    If the HTML font size is 100px, then 1rem=100px, 1px=0.01 REM, so if the design text is given a width of 300px, then the final translation is: 300/2*0.01=1.5rem

Complete code example:

<! doctypehtml>
<html lang="en" style="font-size: 100px;">
	<head>
		<meta charset="UTF-8">
		<meta name="viewport"
			content="Width =device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
		<meta http-equiv="X-UA-Compatible" content="ie=edge">
		<title>adapter</title>
		<style>
			#box {
				width: 2rem;
				height:1rem;
				background: # 886;
			}
		</style>
	</head>
	<body>
		<div id="box"></div>

		<script>
			// // Gets the width of the layout viewport
			// var width = document.documentElement.clientWidth;
			//
			// // calculate the new font size based on iphone6 font size=100px
			// var x = width * 100 / 375;
			//
			// // Set a new font size
			// document.documentElement.style.fontSize = x + 'px';
			
			document.documentElement.style.fontSize = document.documentElement.clientWidth * 100 / 375 + 'px';
			window.onresize = function() {
				document.documentElement.style.fontSize = document.documentElement.clientWidth * 100 / 375 + 'px';
			}
		</script>
	</body>
</html>

Copy the code
Method 2 (recommended) : Use the font size of the root element according to the proportional size of the width of the design draft

Select a font size proportional to the width of the design text for the root element. If the width of the design text is 750px, then the HTML font size=75px(easy to calculate). If the width of the design is 375px, font-size=37.5px for HTML (easy to calculate);

  1. Perfect viewport setup

    <meta name="viewport"
                  content="Width =device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
    Copy the code
  2. Set the font size of the root element of the page with JS (here, set the layout viewport width /10 for ease of calculation)

    document.documentElement.style.fontSize = document.documentElement.clientWidth / 10+ 'px';
    window.onresize = function() {
    				document.documentElement.style.fontSize = document.documentElement.clientWidth / 10+ 'px';
    			}
    Copy the code
  3. Use REM to set the size of elements according to the design draft

    If the HTML font size is 75px, then 1rem=75px, 1px= 1/75REM, so if the design is given a width of 300px, then the final conversion to REM is: 300/75=4rem

    Complete code example:

    <! < HTML lang="en" style="font-size: 36.5px; > <head> <meta charset=" utF-8 "> <meta name="viewport" content="width=device-width, user-scalable=no, initial-scale=1.0, Maximum - scale = 1.0, <meta http-equiv=" x-UA-compatible "content="ie=edge"> <title>rem adaptation </title> 400/37.5 rem. Height: 200/37.5 rem. background: #886; } </style> </head> <body> <div id="box"></div> <script> document.documentElement.style.fontSize = document.documentElement.clientWidth / 10 + 'px'; window.onresize = function() { document.documentElement.style.fontSize = document.documentElement.clientWidth / 10 + 'px'; } </script> </body> </html>Copy the code

    Combined with SCSS, it will be more convenient:

    // Because it is a reference design 750px; If the design is 375px, Function px2rem($px, $base-font-size:75px) { @if (unitless($px)) { @warn "Assuming #{$px} to be in pixels, attempting to convert it into pixels for you"; @return px2rem($px + 0px); } @else if (unit($px)==rem) { @return $px; } @return ($px / $base-font-size) * 1rem; } #box { width: px2rem(400); // 400 is the size measured at 750px height: px2rem(200); background: #886; }Copy the code

11. 1px border issues

1px on an HD screen corresponds to more physical pixels, so the 1-pixel border looks thicker. Here’s how to fix it

Methods a

  1. Borders are implemented using pseudo-class selectors, or separate elements. Like the bottom border
.box2::after {  content: ' ';  height: 1px;  width: 100%;  position: absolute;  left: 0;  bottom: 0;  background: # 000; }Copy the code
  1. Set under hd screen
@media screen and (-webkit-min-device-pixel-ratio: 3) {  .box2 {    transform: scaleY(0.33333);  }}
Copy the code

Method 2

  1. Rem page layout
var fontSize = 50;document.documentElement.style.fontSize = '50'+px;
Copy the code
  1. The border of the element is set to 1px

  2. The entire page is reduced by initial-scale in viewPort

var dpr = window.devicePixelRatio; viewport.setAttribute('content'.'user-scalable=no, initial-scale='+1/dpr + ',user-scalable=no');
Copy the code
  1. Reset the root element font
document.documentElement.style.fontSize = fontSize * dpr + 'px';
Copy the code