Responsive introduction

With the rise of mobile Internet, the resolution of different devices varies greatly. If the same page is displayed on different Settings, the user experience will be poor. Responsive web design is a way to make a web site compatible with multiple terminals without having to make a specific version for each terminal. It makes a website easy to browse and use on any type of screen. With a responsive design, the site rearranges itself to display different design styles on different devices, perfect for any screen size.Copy the code

Design principles

In terms of responsive design, there are two design principles of progressive enhancement and elegant degradation. Progressive enhancement means that basic requirements are met and realized, and new features in advanced browsers are utilized to provide better experience according to the characteristics of different browsers and devices with different resolutions. For example, rounded corners, shadows, animations, and other graceful degradation are the opposite. Existing features are fully developed, but require backward compatible versions and browsers that don't support them. While the compatibility solution doesn't offer the same experience as the conventional solution, the mobile-first responsive layout ensures functional usability using progressive enhancement principles. When creating a responsive website, work on mobile first, then design and develop more complex features for larger devices. The feature is to use min-width to match the page width. When writing from top to bottom, the first consideration is the mobile device usage scenario, the default query is the narrowest case, and then consider the device screen gradually widened from simple to complex, from complex to simple to difficult. If it is desktop first, the layout side is desktop side code, and only in media, it is mobile side code, loading extra desktop side code. If it's an image file, more useless resources are downloaded. Mobile first has a clear advantage both from an interface design perspective and from a code execution efficiency perspectiveCopy the code

How is responsive layout implemented

Three elements of a responsive layout:

  1. Viewport Viewport Settings
  2. @media Media query
  3. Do not write dead size
    • Use the percentage width to determine the layout size
    • Rem and EM are used to determine the layout size
    • Use VH and VW to determine the layout size

See the above three rules, blinded state, let’s go into detail on each one.

Before going to understand mobile responsive, first look at a few responsive sites, to get a feel for it!

Starbucks INSIDE Bootstrap

After looking at the above three site examples, think back to the website we did before but fixed to write dead page !!!! Now let’s get down to business

Viewport Viewport Settings

The concept of viewPort
Generally speaking, a viewport on a mobile device is the part of the screen on the device that can be used to display our web page. In particular, it is the part of the browser (or maybe a Webview in an app) that can display the web page. But a viewport is not limited to the size of the browser's viewport. It may be larger or smaller than the viewable area of the browser. By default, viewPorts on mobile devices are generally larger than the viewport area of the browser. This is because mobile devices have a smaller resolution than desktop computers, so in order to display traditional web sites designed for desktop browsers properly on mobile devices, Browsers on mobile devices will set their default viewPort to 980px or 1024px (or any other value, depending on the device), but the result will be a horizontal scroll bar because the width of the browser's viewport is smaller than the default viewPort width.Copy the code

The following figure lists the default viewPort widths for browsers on some devices.

2. 1px in the CSS is not equal to 1px in the device
In CSS, we usually use PX as the unit. In PC browser, a pixel of CSS usually corresponds to a physical pixel of the computer screen, which may cause an illusion that the pixel in CSS is the physical pixel of the device. However, this is not the case. A CSS pixel is an abstract unit, and the 1px in the CSS represents different physical pixels on different devices or in different environments. We don't have to worry about this when designing a web page for a desktop browser, but on a mobile device, it's important to understand. In earlier mobile devices, screen pixel density was low, such as the iphone3, which had a resolution of 320x480. On the iphone3, one CSS pixel was indeed equal to one physical pixel on the screen. Later, with the development of technology, the pixel density of the screen of mobile devices became higher and higher. Starting from iphone4, Apple introduced the so-called Retina screen, with the resolution doubled to 640x960, but the screen size remained unchanged, which meant that the pixels on the same size screen were doubled. At this time, One CSS pixel is equal to two physical pixels. The same goes for other brands of mobile devices. For example, Android devices can be divided into LDPI, MDPI, HDPI, XHDPI and other different levels according to the pixel density of the screen. The resolution is also varied. How many physical pixels of a CSS pixel on an Android device is equivalent to? Another factor that can cause px changes in CSS is user scaling. For example, when a user doubles the size of a page, the number of physical pixels represented by 1px in the CSS doubles. Conversely, doubling the size of the page will reduce the number of physical pixels represented by 1px in the CSS by twice as much. We'll talk more about this in a later section. In mobile browsers and some desktop browsers, the Window object has a devicePixelRatio property, which is officially defined as the ratio of device physical pixels to device independent pixels, i.e., devicePixelRatio = physical pixels/individual pixels. The PX in the CSS can be regarded as an independent pixel of the device, so by using devicePixelRatio, we can know how many physical pixels a CSS pixel on the device represents. For example, on a Retina iPhone, devicePixelRatio is 2, meaning that one CSS pixel equals two physical pixels. Note, however, that devicePixelRatio has some compatibility issues across browsers, so we can't trust it completely yet. Specific can see [this article] (http://www.quirksmode.org/blog/archives/2012/06/devicepixelrati.html).Copy the code

Test results of devicePixelRatio:

PPK’s theory of three viewports

PPK has a lot of research on viewport on mobile devices (the first, second and third papers), interested students can go to have a look, there are a lot of data and views from there. According to PPK, there are three viewports on mobile devices.

First, browsers on mobile devices think they must be able to make all web sites display correctly, even those not designed for mobile devices. However, if you use the viewport area of the browser as the viewport, because the screen of mobile devices is not very wide, so those websites designed for desktop browser display on mobile devices will inevitably be crowded because of the mobile device viewport is too narrow, and even the layout will be messed up.

Some may ask, aren’t there many phones with very large resolutions, such as 768×1024 or 1080×1920, that are fine for displaying websites designed for desktop browsers?

As we’ve already said, 1px in CSS is not 1px on the screen, the bigger your resolution, the more physical pixels in CSS 1px is, and the bigger the devicePixelRatio is, which makes sense because you’re increasing the resolution, but the screen size isn’t that much bigger, The 1px in CSS must represent more physical pixels, so that 1px objects will be the same size on the screen as those on lower-resolution devices, or they will be too small to see. So on devices like 1080×1920, by default you might just have to set the width of a div to 300-plus pixels (depending on the devicePixelRatio) to get a full screen.

To get back to the point, if the browser’s viewport area is set to viewPort on mobile devices, some websites will display a messy viewPort that is too narrow, so those browsers decide to default to a wider viewport, such as 980px. That way, even websites designed for the desktop will work on mobile browsers. PPK calls this browser’s default viewPort a Layout ViewPort. * the layout viewport width can be through the document. The documentElement. ClientWidth to obtain.

However, the layout viewPort is larger than the viewport of the browser, so we need a viewport to represent the viewport size of the browser. PPK calls this viewPort a Visual ViewPort. The width of the Visual ViewPort can be obtained using window.innerWidth, but not in Android 2, Oprea Mini, or UC 8.

We now have two viewPorts: Layout ViewPort and Visual ViewPort.

But browsers don’t think that’s enough, because more and more websites are individually designed for mobile devices and must have a viewport that works perfectly for mobile devices.

Perfect fit means that, first of all, the user does not need to zoom and horizontal scrollbars to see all the content of the site; Second, the size of the text displayed is appropriate. For example, a 14px text will not be too small to be seen on a high-density screen. Ideally, this 14px text will be displayed in the same size regardless of the screen density and resolution. Of course, not just text, but other elements like images. PPK calls this viewport ideal ViewPort, which is the third viewport — the ideal viewport for mobile devices.

There is no fixed size for the Ideal ViewPort, different devices have different Ideal Viewports. The Ideal ViewPort for all iphones is 320px, whether the screen width is 320 or 640, that is, in the iPhone CSS 320px represents the width of the iPhone screen.

But android devices are more complicated, 320px, 360px, 384px, etc. For the ideal Viewport width of different devices, you can check it at viewportsizes.com, which collects the ideal width of many devices.

conclusion

PPK divides viewPorts on mobile devices into layout ViewPort, Visual ViewPort and Ideal ViewPort.

The ideal ViewPort is the ideal viewport for mobile devices, the width of the ideal Viewport is equal to the screen width of the mobile device, just set the width of an element in the CSS to the ideal Viewport width (in px), The width of this element is the width of the device screen, which is the effect of a width of 100%. The idea of the Ideal ViewPort is that sites designed for the Ideal ViewPort can be presented to the user at any screen resolution without manual scaling or horizontal scrollbars.

4. Use meta tags to control viewPort
The default viewPort for mobile devices is a Layout ViewPort, which is wider than the screen, but for mobile site development we need the Ideal ViewPort. So how do you get the Ideal ViewPort? This is where meta tags come in.Copy the code

One of the most common things we do when developing websites for mobile devices is to copy the following into our head tag:

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

This meta tag makes the width of the current viewPort equal to the width of the device, and does not allow the user to manually scale. You may or may not allow the user to zoom in and out depending on the site, but having the viewPort width equal to the width of the device should be what everyone wants. If you don’t, you’ll use the default viewPort that is wider than the screen, which means a horizontal scroll bar will appear.

What does the meta tag named Viewport have and what does it do?

The Meta ViewPort tag was first introduced by Apple in its Safari browser to solve the viewport problem on mobile devices. Android and other browser vendors followed suit and introduced support for Meta ViewPort, which proved to be very useful.

In the Apple specification, the Meta ViewPort has six properties (let’s call those things in content individual properties and values for now), as follows:

width Set up thelayout viewportIs a positive integer, or the string “width-device”
initial-scale Sets the initial zoom value of the page to a number, possibly with a decimal
minimum-scale The minimum zoom value allowed to the user is a number, which can be a decimal
maximum-scale The maximum zoom value allowed to the user is a number, which can be a decimal
height Set up thelayout viewportThis property is not important to us and is rarely used
user-scalable Whether to allow users to zoom in and out. The value is “no” or “yes”, where “no” means “no” and “yes” means “yes”

These attributes can be used together, individually, or in combination, separated by commas.

5. Set the viewPort width to the ideal ViewPort width

To get the Ideal ViewPort, you must set the default Layout ViewPort width to the screen width of your mobile device. Since width in the Meta ViewPort controls the width of the Layout ViewPort, we only need to set width to the special value width-device.

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

Here’s how this code works on mobile browsers:

You can see that by width=device-width, all browsers can change the current viewPort width to the ideal Viewport width, but it’s important to note that on iPhone and iPad, whether it’s portrait or landscape, The width is the width of the Ideal ViewPort in portrait.

Sure, when we’re developing web pages for mobile devices, whether you know what a viewport is or not, this is probably all you need.

But you don’t know that

<meta name="viewport" content="initial-scale=1">
Copy the code

This code can also achieve the same effect as the previous one, and can also change the current viewport to the Ideal Viewport.

In theory, all this code does is not scale the current page, i.e. the page should be as big as it should be. Width =device-width?

And to figure that out, first you have to figure out what the scaling is relative to, because the scaling here is 1, which means it’s not scaled, but it achieves the Ideal Viewport, so there’s only one answer, the scaling is relative to the Ideal Viewport, When you scale the Ideal ViewPort 100%, that’s 1, you get the Ideal ViewPort. As it turns out, it is.


Test results show that initial-scale=1 also changes the viewPort width to the ideal ViewPort width, But this time it’s Internet Explorer on Windows Phone that sets the width of the Ideal ViewPort for portrait and landscape. But that little flaw doesn’t matter anymore.

But what if width and initial-scale=1 are both present and there is a conflict? Such as:

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

Width =400 sets the current viewport width to 400px and initial-scale=1 sets the current viewport width to the ideal Viewport width. Is it the one that’s written on the back? It isn’t. When this happens, the browser takes the larger of the two. For example, when width=400 and ideal ViewPort width is 320, select 400; When width=400 and the ideal Viewport width is 480, the ideal Viewport width is taken. In UC9, when initial-scale=1, the width of the viewPort will always be the width of the ideal Viewport regardless of the width property value.

And finally, to summarize, to set the current viewport width to the ideal Viewport width, you can either set width=device-width or initial-scale=1, but there’s a small flaw in both, The ideal ViewPort width is the same for iPhone, iPad and Internet Explorer. Initial-scale =1; width=device-width =1; width=device-width =1;

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

How @media is used

[1] The first kind of direct embedding

@media (max-with: 480px) {body{
        background-color: red; }}Copy the code

[2] The second external connection mode

<link rel="stylesheet" media="max-width: 480px" href="css/viewport.css">
Copy the code

The media type

The media property is used to specify different styles for different media types

Screen computer screen (default) TTY teleprinter and similar media TV tV-type devices using the same width character grid (low resolution, limited screen tumble capability) projection projector handheld devices (small screen, limited bandwidth) print Braille for the blind feedback device Aural voice synthesizer all suitable for all devicesCopy the code

The media types that are really widely used and compatible with all browsers are Screen and All

** demonstrates the default screen and print**

<! DOCTYPEhtml>
<html lang="zh-CN">
  <head>
    <meta charset="utf-8">
    <title>Media Type - Media Type</title>
		<meta name="viewport" content="width=device-width,initial-scale=1,minimum-scale=1,maximum-scale=1,user-scalable=no" />
    <link rel="stylesheet" href="css/style.css">
    <link rel="stylesheet" href="css/print.css" media="print">
  </head>
  <body>
    <h1>Meida Type</h1>
  </body>
</html>
Copy the code

style.css

/* The default device background color is black, font color */
body{
	background-color: # 000000;
	color: #fff;
}
Copy the code

print.css

/* Under printer device */
body{
	background-color: #fff;
	color: # 000;
}
Copy the code

Results show that

Media properties

When setting up the media query, we use expressions to determine media characteristics such as resolution, height, width, aspect ratio, device aspect ratio, device width and height, and screen orientation (landscape or portrait).

Now take horizontal and vertical screen as an example to demonstrate the effect

Landscape * / / *
@media (orientation: landscape) {
    body{
        background-color: #008B8B; }}/ * * / vertical screen
@media (orientation: portrait) {
    body{
        background-color: #4169E1;
}
Copy the code

Effect:

Width and height

Represents the width and height of the screen. You can also prefix Max and min.

/* Less than 640px */
body {
    background-color: # 000;
    color: #fff;
}
/* You can use either and or the OR concatenator */ between styles 640 and 991
@media all and (min-width: 640px) and (max-width: 991px) {
    body{
        background-color: blueviolet; }}/* Style between 992px and 1189px and display green in landscape */
@media (max-width:1189px) and (min-width: 992px) , screen and (orientation: portrait){
    body{
        background-color: green; }}/* Larger than 1190px style */
@media (min-width:1190px) {
    body{
        background-color: red; }}Copy the code

Responsive picture

[1] Use the IMG tag to set the display of pictures

/* The simple solution is to use percentages, but this is not friendly and will enlarge or shrink the image. Try to specify a maximum width of percentages for the image. If the image exceeds, zoom out. If the image is too small, print the original size */
img{
	width: 100%;
	max-width: 100%;
} 
Copy the code

[2] Use the background property to set the background image

Setting background-size to cover expands the background image large enough to completely cover the background area.

.bg_img{
	background: url(../images/01.jpg) no-repeat center center;
	background-size: cover;
	height: 500px;
}
Copy the code

Rem adaptive layout

In the overall layout of the page, the size of the page elements (length, width, inside and outside margins, etc.) and the size of the page font are also important. With the right Settings, the page will look well structured, focused and pleasing to the eye. On the other hand, an unfriendly setting of page size and font size will increase the complexity of the page and the complexity of the user’s understanding of the page. Even accessing devices today (iPhone, iPad, PC, Android…) Today’s endless, adapt to a variety of access terminals, will become a “hot potato”. So in recent years, “nine grid” type “flow layout” return. In order to provide page layout and other maintainability and extensibility, we tried to set the size of page elements, as well as the font size, to relative values instead of isolated fixed pixels. It allows the child element to adapt to changes in size as the parent element changes. Bootstrap and other CSS frameworks are on the rise, combined with a handful of the latest CSS3 @media queries for “responsive layouts.”

In CSS, however, the W3C document classifies units of size into two categories: relative and absolute

Absolute unit

Px: Pixels are absolute units. How many pixels you set will remain the same no matter what screen is underneath. Disadvantages: Fixed value in all casesCopy the code

Relative unit

% : relative unit, it is relative to the parent (itself) to locate size Faults: can determine the range or better, for the determination of is not very good value percentage is bad to use, and can lead to deformation, highly generally bad control em: relative to the current container to change the font size Such as the font size for the current container20px, then1em = 20pxDisadvantages: The font size of the current container will change, assuming that each container font size is not the same, then the calculation is very tedious rem:font size of the root element. Changes the font size relative to the current root (HTML) element such as the current HTML font size20px, then1rem = 20px; Browser default1rem = 16px
Copy the code
How do you use REM for adaptation?
  • The font size
    • The value is based on the size of the HTML root element, and can also be used as a width, height, etc
  • Principle of adaptation
    • Replace PX with REM to dynamically change HTML font size fit
  • compatibility
    • Ios6 above and android2.1 above, basic coverage of all popular mobile phone systems

Here’s an example:

<! DOCTYPEhtml>
<html>
	<head>
		<meta charset="utf-8">
		<title></title>
		<meta name="viewport" content="width=device-width,initial-scale=1,minimum-scale=1,maximum-scale=1,user-scalable=no" />
		<style type="text/css">
			* {
				padding: 0;
				margin: 0;
			}
			ul{
				list-style: none;
			}
			html{
				width: 100%;
				height: 100%;
			}
			body{
				width: 100%;
				height: 100%;
			}
			.head-box{
				width: 100%;
				height: 70px;
				background-color: # 000000;
				
			}
			.list .item{
				float: left;
				width: 100px;
				height: 100px;
				margin: 20px;
				border: 1px solid red;
				font-size: 14px;
			}
		
			
		
		</style>
		<script src="js/resize.js" type="text/javascript" charset="utf-8"></script>
	</head>
	<body>
		<header class="head-box">
			<div class="head-top"></div>
			<div class="head-bottom"></div>
		</header>

		<ul class="list clearfix">
			<li class="item">1111111</li>
			<li class="item"></li>
			<li class="item"></li>
			<li class="item"></li>
			<li class="item"></li>
			<li class="item"></li>
			<li class="item"></li>
			<li class="item"></li>
		</ul>
	</body>
</html>

Copy the code

Display effect:

Set the HTML font size to 50px, and change the width, height and margins of the box to REM.

html{
    width: 100%;
    height: 100%;
    font-size: 50px;
}
.list .item{
    float: left;
    width: 2.0 rem;
    height: 2.0 rem;
    margin: 0.2 rem;
    border: 1px solid red;
    font-size: 14px;
}
Copy the code

But if you’re on an iPad, you’d normally expect to see three boxes on one row. If you manually increase the size of the font size, you can achieve the desired effect.

Dynamically change font size
window.addEventListener('resize'.function(){
    var htmlWidth = document.documentElement.clientWidth || document.body.clientWidth;
    document.getElementsByTagName('html') [0].style.fontSize =(htmlWidth / 750) * 100 + 'px';
});
Copy the code

According to iphone678 as an example, then the HTML font size is 50px, then 1rem = 50px; 1 px = 0.02 rem

Complete dynamic modification of HTML font size JS files

! (function(doc, win) {
	var docEl = doc.documentElement,
		resizeEvt = 'onorientationchange' in window ? 'onorientationchange' : 'resize',
		recalc = function() {
			var clientWidth = docEl.clientWidth;
			if(! clientWidth)return;
			if (clientWidth >= 750) {
				docEl.style.fontSize = '100px';
			} else {
				docEl.style.fontSize = 100 * (clientWidth / 750) + 'px';
			}
			docEl.style.fontSize = 100 * (clientWidth / 750) + 'px';
		};

	if(! doc.addEventListener)return;
	win.addEventListener(resizeEvt, recalc, false);
	doc.addEventListener('DOMContentLoaded', recalc, false); }) (document.window);
Copy the code
flexiable.js

Flexiable. js is the best H5 mobile adaptation solution proposed by Taobao official. website

Hbuilderx’s PX to REM tool is handy, but what if you don’t have one? It’s time to learn less and sass. They are a pre-processed CSS language. In the next chapter.

less

Define variables

In less files, we can declare variables

@color: #f00;
h2{
    color: @color;
}
Copy the code
Minxins mixed with

Minxins are a way of mixing a set of attributes from one rule set into another.

@color: #f00;
@width: 100px;
@height: @width;
.active{
	border: 1px solid @color;
	width: @width;
	height: @height;
}
#box2{
    /* Intermixed with.active rules */
	.active;
}
Copy the code
Nested rules

Less can use nested rules to write our code

It has the following structure

<div id="box">
    <h2>
        <span>Mjj</span>
    </h2>
</div>
Copy the code

Previous CSS writing:

#box {
  width: 100px;
  height: 100px;
  border: 1px solid # 000;
}
#box h2 {
  background-color: green;
  padding: 20px;
}
#box h2 span {
  color: #f00;
}
Copy the code

Written using less nesting rules

@color: #f00;
@width: 100px;
@height: @width;
#box{
	width: @width;
	height: @height;
	border: 1px solid # 000;
	h2{
		background-color: green;
		padding: 20px;
		span{
			color: @color; }}}Copy the code

The generated code is more concise and mimics the structure of HTML

operation

The arithmetic operators +,-,*,/ can be used in less

@a: 20px;
@b: 30px;
@sum = @a + @b;

.active{
    width: @sum;
}
Copy the code
escape

It allows you to use any string as an attribute or variable value. Anything inside ~”anything” is used as-is. Nothing changes except interpolation.

// Insert the variable @min768, equivalent to (min-width:768px) fully inserted
@min768:~"(min-width:768px)";
body{
	@media @min768 {
		background-color: red; }}// After compiling
@media (min-width:768px) {
  body {
    background-color: red; }}Copy the code
The variable interpolation

Selector names can be used as mutable values

// Define your own selector
@my-selector: banner;
// Use your own selector
.@{my-selector}{
	font-size: 30px;
}

/ / compile
.banner{
    font-size: 30px;
}
Copy the code

Url insert

// Variables
@images: ".. /img";

// Usage
body {
  color: # 444;
  background: url("@{images}/white-sand.png");
}
Copy the code

Import statements

@import './hello.less'
Copy the code
The parent selector

& references the parent selector

a {
  color: blue;
  &:hover {
    color: green; }}/ / compile
a {
  color: blue;
}

a:hover {
  color: green;
}
Copy the code

If you look at this example, maybe you can see the power of ampersand

.button {
  &-ok {
    background-image: url("ok.png");
  }
  &-cancel {
    background-image: url("cancel.png");
  }

  &-custom {
    background-image: url("custom.png"); }}/ / compile
.button-ok {
  background-image: url("ok.png");
}
.button-cancel {
  background-image: url("cancel.png");
}
.button-custom {
  background-image: url("custom.png");
}
Copy the code
Custom function

@base:375 / 375 * 0.01;
// Custom functions
.px2rem(@name.@px) {
     @{name}: @px * @base * 1rem;
}
// Use custom functions
.footer{
	font-size: 20px;
	.px2rem(padding,30);
}
Copy the code

Mobile event

Touch events

Triggered when we place our finger on the screen, swipe on it, or move away from it. Specifically, there are the following touch events

1.Touchstart: triggered when a finger touches the screen; Trigger even if a finger is already on the screen2.Touchmove: Triggered continuously when a finger is swiped across the screen. Call preventDefault() to prevent scrolling during this event3.Touchend: Triggered when the finger is removed from the screen4.Touchcancel: Triggered when the system stops tracking a touch (uncommon). The exact timing of this event is not specified in the documentationCopy the code
<! DOCTYPEhtml>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <title>Document</title>
    <meta name="viewport" content="Width =device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
    <style type="text/css">
    .box {
        width: 200px;
        height: 200px;
        background-color: red;
    }
    </style>
</head>

<body>
    <! -- 1. Common events on mobile -->
    <! -- TouchStart triggers touchMove when a finger is pressed down on the screen -- TouchMove triggers touchEnd when a finger is lifted up on the screen, or when a finger is drawn across the screen -->
    <div class="box">
    </div>
    <script type="text/javascript">
    window.onload = function() {
        var oDiv = document.querySelector('.box');
        oDiv.addEventListener('touchstart'.function(event) {
            console.log('Got my finger down');
        }, false);
        oDiv.addEventListener('touchmove'.function(event) {
            console.log('touchmove');
        }, false);
        oDiv.addEventListener('touchend'.function(event) {
            console.log('touchend');
        }, false);
    }
    </script>
</body>

</html>
Copy the code

Touch event object

The properties of the event object are stored in the Touches array

ClientX: Touch the x coordinate of the target in the viewport. ClientY: Touch the target's y coordinate in the viewport. Identifier: Unique ID that identifies a touch. PageX: Touch the x coordinate of the target in the page. PageY: Touch the y coordinate of the target on the page. ScreenX: Touches the x coordinate of the target on the screen. ScreenY: Touches the y coordinate of the target on the screen. Target: the target of the DOM node that you see.Copy the code

Sliding implementation

  1. Let the touch element change position as the finger slides
  2. Changes in position require the coordinates of the current finger
  3. The coordinates of the current touch point are recorded in each touch point. E.touches [0] the first touch point
ClientX clientY Based on browser window (viewport) pageX pageY based on page (viewport) screenX screenY based on screenCopy the code

Wrap: Swiper gesture event

Including: swipeLeft swipeRight, swipeUp swipeDown

<! DOCTYPEhtml>
<html lang="en">

    <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="Width = device - width, initial - scale = 1.0">
        <meta http-equiv="X-UA-Compatible" content="ie=edge">
        <title></title>
    </head>

    <body>
        <div class="box" style="width: 200px; height: 200px; background-color: pink;"></div>
        <script>
            // The encapsulation slides left to interact right

            function swiper(ele, options) {
                var startX;
                var startY;
                var disX;
                var disY;
                var moveX;
                var moveY;
                // There is no touch touch move event by default
                var isMove = false;
                // 1. Bind the element to touch the start event, passing in the event object
                ele.addEventListener('touchstart'.function (e) {
                    // 2. Click to record the coordinates of sliding
                    startX = e.touches[0].clientX;
                    startY = e.touches[0].clientY;
                    disX = startX - ele.offsetLeft;
                    disY = startY - ele.offsetTop;

                })
                ele.addEventListener('touchmove'.function (e) {
                    // 3. The starting coordinates are recorded above, the moving mouse X coordinates
                    moveX = e.touches[0].clientX;
                    moveY = e.touches[0].clientY;

                    // Change the current state, indicating that the user finger touch moved
                    isMove = true;
                    // console.log(disX);
                    e.info = {
                        startX: startX,
                        startY: startY,
                        disX: disX,
                        disY: disY
                    }
                })
                ele.addEventListener('touchend'.function (e) {
                    // 4. Check whether the user has enabled the touch movement event.
                    if (isMove) {

                        // 5. Determine whether the user is swiping horizontally or vertically
                        var absX = Math.abs(moveX - startX);
                        var absY = Math.abs(moveY - startY);
                        If the x axis is larger than the y axis, it will be horizontal, otherwise vice versa
                        if (absX > absY) {
                            // console.log(' horizontal swipe ');
                            // 7. If you have moved farther than you started, swipe to the right, otherwise to ⬅️
                            moveX > startX ? options.swipeRight() : options.swipeLeft();
                        } else {
                            // console.log(' vertical swipe ');
                            moveY > startY ? options.swipeDown() : options.swipeUp();
                        }
                        isMove = false;
                    }
                })
            }
            swiper(document.querySelector('.box'), {
                swipeLeft: function () {
                    console.log('Swipe left')},swipeRight: function () {
                    console.log("Swipe right");

                },
                swipeDown: function () {
                    console.log('Slide down')},swipeUp: function () {
                    console.log("Slide up"); }})</script>
    </body>

</html>
Copy the code

Solution of 300ms delay on mobile terminal

In general, if there is no special processing, the mobile browser will usually have a delay of about 300ms when sending click events. In other words, mobile browsers do not react immediately when we click on a page, but wait a little while for the click to appear. In the early days of the mobile WEB, the 300ms delay was not obvious to users. However, as users have higher and higher requirements for interactive experience, the 300ms click delay on mobile terminals has become increasingly obvious and intolerable. So where does the 300ms click delay on mobile come from?

Origin of 300ms delay

This dates back to the beginning of 2007. In the run-up to the launch of apple's first iPhone, the company had a problem: Its website was designed for devices with larger screens. So Apple's engineers made conventions to deal with the small screen of the iPhone when browsing desktop sites. The most famous of these is the double tap to Zoom, which is the main reason for the 300-millisecond delay. Double zoom, as the name suggests, involves two quick finger taps on the screen, and the Safari browser that comes with iOS scales the web to its original proportions. So what does this have to do with the 300 millisecond delay? Consider this scenario. 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. Before, when people just touched the page of mobile terminal, they would not care about the 300ms delay. However, now the interface of touch terminal is mushroomed and users have higher requirements for experience. The lag caused by 300ms gradually becomes unacceptable.Copy the code

To solve

The first step is to introduce in the head tag

<script src="https://cdn.bootcss.com/fastclick/1.0.6/fastclick.js"></script>
Copy the code

Step 2, after loading the fastclick.js script

document.addEventListener('DOMcontentLoaded'.function() {
    FaskClick.attach(document.body);
}) 
document.querySelector('a').addEventListener('click'.function() {
    // The normal click response is significantly faster
    console.log('click');
})
Copy the code

Mobile terminal common library zepto.js

At present, the library we use on the PC side is usually jQuery, while a zepto.js is launched on the mobile side. What are its advantages over jQuery?

1. In terms of size, the size of zepto.min.js after compression is only 21K, and the size of zepto.min.js after compression using server-side gzip is only 5-10K, which can be said to be very small.

2. It’s small, but it’s full of features, with a few more touch-screen events. It’s a good choice for developing iPhone and Android web pages, but it doesn’t support Internet Explorer.

3. Zepto is a simplified version of jQuery, removing a lot of jQuery compatible code for mobile terminals.

4. Zepto’s core library performs better than jQuery because of its simplicity.

Zepto. Js’s official website

Note: Zepto.js touch event does not work, why?? Well, I’m definitely giving up on this mobile library. It seems that vue rules. Mobile libraries like Vux and iVew are definitely better than zepto.js. Oh, my god, you’re gonna kill me

Swiper is a common mobile library

Swiper is a JavaScript plugin for sliding effects.

Swiper is an open source, free, stable, easy to use, powerful and important choice for building mobile websites. Swiper can be used to switch between focus images, Tab images and multiple images

Swiper4. x Usage method

Swiper4. x Usage method

<! DOCTYPEhtml>
<html lang="en">

    <head>
        <meta charset="utf-8">
        <title>Swiper demo</title>
        <meta name="viewport" content="width=device-width, initial-scale=1, minimum-scale=1, maximum-scale=1">

        <! -- Link Swiper's CSS -->
        <link rel="stylesheet" href="css/swiper.min.css">

        <! -- Demo styles -->
        <style>
            html.body {
                position: relative;
                height: 100%;
            }

            body {
                background: #eee;
                font-family: Helvetica Neue, Helvetica, Arial, sans-serif;
                font-size: 14px;
                color: # 000;
                margin: 0;
                padding: 0;
            }

            .swiper-container {
                width: 100%;
            }

            .swiper-slide {
                text-align: center;
                font-size: 18px;
                background: #fff;

                /* Center slide text vertically */
                display: flex;
                justify-content: center;
                align-items: center;
            }

            img {
                width: 100%;
            }
            .my-bullet-active{
                background-color: yellow;
                opacity: 1;
            }
        </style>
    </head>

    <body>
        <! -- Swiper -->
        <div class="swiper-container">
            <div class="swiper-wrapper">
                <div class="swiper-slide">
                    <a href="javascript:void(0)"><img src="images/01.jpg" alt=""></a>
                </div>
                <div class="swiper-slide">
                    <a href="javascript:void(0)"><img src="images/02.jpg" alt=""></a>
                </div>
                <div class="swiper-slide">
                    <a href="javascript:void(0)"><img src="images/03.jpg" alt=""></a>
                </div>
            </div>
            <! -- Next and last -->
            <! -- <div class="swiper-button-next"></div> -->
            <! -- <div class="swiper-button-prev"></div> -->
            <! -- Add pager -->
            <div class="swiper-pagination"></div>
            <! -- Pager. If placed outside swiper-Container, you need to customize the style. -->
        </div>
        <! -- Swiper JS -->
        <script src="js/swiper.min.js"></script>

        <! -- Initialize Swiper -->
        <script>
            var swiper = new Swiper('.swiper-container', {
                dicreaction:'horizontal'.grabCursor:true.autoplay: true.// Whether to play automatically
                loop: true.// Set an infinite loop
                navigation: {
                    nextEl: '.swiper-button-next'.prevEl: '.swiper-button-prev',},pagination: {
                    el: '.swiper-pagination'.bulletActiveClass: 'my-bullet-active'.// Define the class name}});</script>
    </body>

</html>
Copy the code