Web APIs-day07


foreword

learning target:

Be able to write mobile touch screen events Be
able to write common mobile effects Be
able to use mobile development plug-ins to develop mobile effects Be
able to use mobile development frameworks to develop mobile effects
Be able to write sessionStorage data storage and get and
be able to write localStorage data storage and retrieval
can tell the difference between the two


提示:以下是本篇文章正文内容,下面案例可供参考

1. Touch screen events

1.1 Overview of touch screen events

The compatibility of mobile browsers is good. We don't need to consider the compatibility of JS in the past, and we can use native JS to write the effect with confidence, but the mobile terminal also has its own unique features. For example, the touch screen event touch (also called touch event), both Android and IOS have. The touch object represents a touch point. The touch point may be a finger or a stylus. Touch events respond to user finger (or stylus) operations on the screen or trackpad.

Common touch screen events are as follows:
insert image description here

1.2 Touch Event Object (TouchEvent)

TouchEvent is a class of events that describe the state change of a finger on a touch plane (touch screen, touchpad, etc.). This type of event is used to describe one or more touchpoints, allowing developers to detect movement of touchpoints, increase and decrease of touchpoints, etc.

The three events touchstart, touchmove, and touchend will have their own event objects.

Touch event object focus Let's look at three common object lists:
insert image description here
because we usually register touch events for elements, so focus on remembering targetTocuhes

1.3 Mobile elements on mobile

  1. touchstart, touchmove, touchend can drag elements
  2. But dragging the element requires the coordinate value of the current finger. We can use pageX and pageY in targetTouches[0]
  3. The principle of dragging on the mobile terminal: During the movement of the finger, the distance of the finger movement is calculated. Then use the original position of the box + the distance moved by the finger
  4. Distance the finger moved: the position in the swipe minus the position the finger first touched

Drag element triad:

(1) Touch element touchstart: Get the initial coordinates of the finger, and at the same time get the original position of the box

(2) Move the finger touchmove: Calculate the sliding distance of the finger and move the box

(3) Leave the finger touchend:

Note: Finger movement will also trigger scrolling, so here to prevent the default screen scrolling e.preventDefault();

2. Common special effects on mobile terminals

2.1 Case: Mobile Carousel

移动端轮播图功能和基本PC端一致。

  1. Can play pictures automatically
  2. Fingers can drag to play the carousel

2.2 Case study:

  1. Autoplay function

  2. start timer

  3. Mobile mobile, you can use translate to move

  4. If you want the picture to move gracefully, add a transition effect
    insert image description here

  5. Autoplay feature - seamless scrolling

  6. Note that our judgment condition is to wait until the picture is scrolled before judging, which is to judge after the transition is completed.

  7. At this point, you need to add the detection transition completion event transitionend

  8. Judgment condition: If the index number is equal to 3, it means that the last picture is reached, and the index number should be restored to 0 at this time.

  9. At this point the picture, remove the transition effect, and then move

  10. If the index number is less than 0, it means walking backwards, and the index number is equal to 2

  11. At this point the picture, remove the transition effect, and then move
    insert image description here

2.3 classList attribute

The classList attribute is a new attribute in HTML5 that returns the class name of the element. But ie10 and above versions support it.

This property is used to add, remove and toggle CSS classes on the element. There are the following methods:
element.classList.add('class name');

focus.classList.add('current');

Remove class:

element.classList.remove(’类名’);

focus.classList.remove('current');

Switch class:

element.classList.toggle ('class name');

focus.classList.toggle('current');

注意:以上方法里面,所有类名都不带点

2.4 Case study

  1. Small dots follow the change effect

  2. Select the li with the current class name in the ol to remove the class name remove

  3. Let the small li of the current index number add current add

  4. However, it is waiting for the transition to end, so this is written in the transitionend event

insert image description here
insert image description here

  1. Finger swipe carousel
  2. The essence is that the ul moves with the finger, in short, the mobile terminal drags the element
  3. Touch element touchstart: Get the initial coordinates of the finger
  4. Move the finger touchmove: Calculate the sliding distance of the finger and move the box
  5. Leave the finger touchend: according to the distance of the sliding points
  6. If the moving distance is less than a certain pixel, it will bounce back to the original position
  7. If the moving distance is greater than a certain pixel, it will slide up and down.
  8. Sliding is also divided into left sliding and right sliding. The criterion for judgment is that the moving distance is positive or negative. If it is a negative value, it is left sliding and right sliding.
  9. If you swipe left, play the next one (index++)
  10. If you swipe right, play the previous one (index–)

2.6 Case: back to top

When the page scrolls somewhere, show it, otherwise hide it

Click to go back to top

2.7 Case study

  1. scroll somewhere to show
  2. Event: scroll page scroll event
  3. If the scrolled header (window.pageYOffset) is greater than a certain value
  4. Click, window.scroll(0,0) returns to the top
    insert image description here

3. Click delay solution

The mobile click event will have a delay of 300ms, because the double tap on the mobile screen will zoom the page (double tap to zoom).

solution:

​ 1. Disable scaling. The browser disables the default double-tap to zoom behavior and removes the 300ms click delay.

  <meta name="viewport" content="user-scalable=no">

​ 2. Use the touch event to encapsulate this event yourself to solve the 300ms delay.

The principle is:

  1. When our finger touches the screen, record the current touch time
  2. When our finger leaves the screen, subtract the touch time from the time we left the screen
  3. If the time is less than 150ms and the screen has not been swiped, then we define it as a click

code show as below:

//封装tap,解决click 300ms 延时
function tap (obj, callback) {
    
    
        var isMove = false;
        var startTime = 0; // 记录触摸时候的时间变量
        obj.addEventListener('touchstart', function (e) {
    
    
            startTime = Date.now(); // 记录触摸时间
        });
        obj.addEventListener('touchmove', function (e) {
    
    
            isMove = true;  // 看看是否有滑动,有滑动算拖拽,不算点击
        });
        obj.addEventListener('touchend', function (e) {
    
    
            if (!isMove && (Date.now() - startTime) < 150) {
    
      // 如果手指触摸和离开时间小于150ms 算点击
                callback && callback(); // 执行回调函数
            }
            isMove = false;  //  取反 重置
            startTime = 0;
        });
}
//调用  
  tap(div, function(){
    
       // 执行代码  });

  1. Use plugins. fastclick plugin to resolve 300ms delay.
  2. insert image description here

Fourth, the mobile terminal commonly used development plug-ins

4.1 What is a plugin

The mobile terminal requires rapid development, so we often use some plug-ins to help me complete the operation, so what is a plug-in?

JS plug-in is a js file, which is written in accordance with certain specifications, which is convenient for program display effects, has specific functions and is easy to call. Such as carousel and waterfall plugins.

Features: It generally exists to solve a certain problem, its function is single, and it is relatively small.

The animate.js we wrote before is also one of the simplest plugins

fastclick plugin to resolve 300ms delay. use delay

GitHub official website address: https:// [github.com/ftlabs/fastclick](

4.2 Use of plugins

  1. Import js plugin files.

  2. Use according to the prescribed syntax.

  3. fastclick plugin to resolve 300ms delay. use delay

  4. GitHub official website address: https://github.com/ftlabs/fastclick

    if ('addEventListener' in document) {
          
          
                document.addEventListener('DOMContentLoaded', function() {
          
          
                           FastClick.attach(document.body);
                }, false);
    }
    

4.3 Use of swiper plugin

Chinese official website address: https://www.swiper.com.cn/

  1. Import plugin related files.
  2. Use according to the prescribed grammar

4.4 Other common mobile plug-ins

lsuperslide: http://www.superslide2.com/

l scroll : https://github.com/cubiq/iscroll

4.5 Summary of plugin usage

1. Confirm the function implemented by the plug-in

2. Go to the official website to view the instructions for use

3. Download the plugin

4. Open the demo instance file, view the related files that need to be imported, and import

5. Copy the structure html, style css and js code in the demo instance file

4.6 Mobile video plugin zy.media.js

H5 gives us the video tag, but browser support is different.

Different video format files, we can solve it through source.

But the appearance style, as well as pause, play, full screen and other functions, we can only write code to solve it.

At this time, we can use the plug-in method to make it.

We can modify the size, color, position and other styles of elements through JS.

5. Common development frameworks for mobile terminals

5.1 The difference between plugins and frameworks

A framework, as its name implies, is a set of architectures, which will provide users with a relatively complete set of solutions based on its own characteristics. The control of the framework lies in the framework itself, and users should develop according to certain specifications stipulated by the framework.

Plug-ins generally exist to solve a certain problem, and their functions are single and relatively small.

Commonly used front-end frameworks include Bootstrap, Vue, Angular, React, etc. Can develop both PC and mobile terminals

Commonly used mobile plug-ins in the front end include swiper, superslide, iscroll, etc.

Framework: Big and comprehensive, a complete set of solutions

Plugin: Small and specific, a solution for a certain function

5.2 Bootstrap

Bootstrap is a concise, intuitive and powerful front-end development framework that makes web development faster and easier.

It can develop PC and mobile terminals

Steps to use the Bootstrap JS plugin:

1. Introduce relevant js files

2. Copy the HTML structure

3. Modify the corresponding style

4. Modify the corresponding JS parameters

6. Local storage

With the rapid development of the Internet, web-based applications have become more and more common, and at the same time, they have become more and more complex. In order to meet various needs, a large amount of data is often stored locally. The HTML5 specification proposes related solutions. Program.

6.1. Local Storage Features

1. Data is stored in the user's browser

2. Easy to set and read, even page refresh without losing data

3. Large capacity, sessionStorage is about 5M, localStorage is about 20M

4. Only strings can be stored, and objects can be stored after encoding JSON.stringify()

6.2 window.sessionStorage

1. The life cycle is to close the browser window

2. Data can be shared in the same window (page)

3. Store and use in the form of key-value pairs

Storing data:

sessionStorage.setItem(key, value)

retrieve data:

sessionStorage.getItem(key)

delete data:

sessionStorage.removeItem(key)

Clear data: (all clear)

sessionStorage.clear()

6.3.window.localStorage

1. The declaration cycle takes effect permanently, and the closing page will also exist unless it is manually deleted.

2. Multiple windows (pages) can be shared (the same browser can be shared)

  1. Stored in the form of key-value pairs

Storing data:

localStorage.setItem(key, value)

retrieve data:

localStorage.getItem(key)

delete data:

localStorage.removeItem(key)

Clear data: (all clear)

localStorage.clear()

6.4. Case: Remember Username

If the Remember username is checked, the next time the user opens the browser, the last logged-in username will be automatically displayed in the text box.

case analysis

  1. Store data in local storage

  2. Close the page, you can also display the user name, so use localStorage

  3. Open the page, first determine whether there is this user name, if so, display the user name in the form, and check the checkbox

  4. change event when the checkbox is changed

  5. If checked, save it, otherwise remove it

insert image description here

Finish

Guess you like

Origin blog.csdn.net/qq_44588612/article/details/124076029