Table of Contents
Principle
html&css
js
Set the initial state
First implement a doubly linked list to maintain the elements in the carousel component.
touchstart event
When the finger is pressed, the initial position is saved
The finger slides on the screen, and the page moves with the finger
When the finger leaves the screen, calculate which page it needs to end up on
For ease of use, I encapsulated the entire implementation process into a library and added
H5 single page gesture sliding screen switching principle
Home Web Front-end H5 Tutorial An example tutorial on implementing a carousel (touch screen version) using H5

An example tutorial on implementing a carousel (touch screen version) using H5

May 05, 2017 pm 03:21 PM

I am new to the front-end, and I would like to share the implementation process of the touch screen carousel on the mobile phone. The general functions are as follows:

  1. Supports circular sliding

  2. The width can be set arbitrarily and does not need to be the same width as the screen

  3. The page can be scrolled vertically

  4. The switching of callback listening elements can be set

  5. Pure js, without any third-party library

Principle

  1. Assumption of child elements The width of .item is 375px, use absolute positioning to place all child elements within the parent element

  2. Place the parent element .carousel## The width is set to 375px, which is the same width as the child element .item

  3. is added to the parent element

    .carousel Touch events: touchstart, touchmove, touchend

  4. When the finger is pressed, the initial position is saved (

    clientX)

  5. When the finger slides, the sliding direction is judged by the sliding distance:

    1. If the finger slides to the left, then Move the current element and the element to the right of the current element at the same time

    2. Swipe your finger to the right to move the current element and the element to the left of the current element at the same time

  6. When the finger is lifted, the sliding distance is used to determine whether to switch to the next page

    1. If the moving distance does not exceed 50% of the width of the child element, the current page will be rolled back to Initial position, does not switch the current element.

    2. The movement distance exceeds 50% of the width of the child element and switches the current element to the next element.

    3. Set the

      transform attribute of the current element to translate3d(0px, 0px, 0px) and change z-indexAttribute+1

    4. Set the

      transform attribute of the next child element to translate3d(375px, 0px, 0px), and z-indexAttribute+1

    5. Set the

      transform attribute of the previous child element to translate3d(-375px, 0px, 0px), and set the z-index attribute +1

    6. and set the

      z-index attribute of all other child elements to Default value

  7. The previous element of the first child element is the last element, and the next element of the last element is the first element. This step is implemented through a circular linked list .

When moving, the transform attribute of the child element .item is set, not the parent element

.carousel

## Implementation Steps

html&css

//html
<p class="carousel" ontouchstart="" >  
  <p class="item" style="background: #3b76c0" >    
    <h3 >item-1</h3>  
  </p>  
  <p class="item" style="background: #58c03b;">    
    <h3>item-2</h3>  
  </p>  
  <p class="item" style="background: #c03b25;">    
    <h3>item-3</h3>
  </p> 
  <p class="item" style="background: #e0a718;">  
    <h3>item-4</h3>  
  </p>  
  <p class="item" style="background: #c03eac;">    
    <h3>item-5</h3>  
  </p>
</p>

//css
.carousel{
  height: 50%;
  position: relative;
  overflow: hidden;
}

.item {
  position: absolute;
  left: 0;
  top: 0;
  width: 100%;
  height: 100%;
}
Copy after login

js

Set the initial state

function Node(data) {
    this.data = data;
    this.prev = null;
    this.next = null;
    this.index = -1;
}

//双向循环列表
function LinkList() {
    var _nodes = [];
    this.head = null;
    this.last = null;

    if (typeof this.append !== "function") {
        LinkList.prototype.append = function (node) {
            if (this.head == null) {
                this.head = node;
                this.last = this.head;
            }
            else {
                this.head.prev = node;
                this.last.next = node;

                node.prev = this.last;
                node.next = this.head;

                this.last = node;
            }

            node.index = _nodes.length; //务必在push前设置node.index
            _nodes.push(node);
        }
    }
}
Copy after login

After you have the linked list, create a linked list instance, add the child elements to the linked list, and set some initial states

var _container = document.querySelector("." + containerClass);
var _items = document.querySelectorAll("." + itemClass);

var list = loop ? new LinkList() : new SingleList();
for(var i = 0; i < _items.length; i++) {
  list.append(new Node(_items[i]));
}

var _prev = null;  //保存之前显示的元素
var _current = list.head;  //保存当前显示的元素,默认为第一个元素

var _normalZIndex = _current.data.style.zIndex;  //未显示元素的z-index值
var _activeZIndex = _normalZIndex + 1;  //当前显示元素的z-index值

var _itemWidth = _current.data.offsetWidth; //子元素宽度

positionItems(); //初始化元素位置
zindexItems(_current, _activeZIndex); //将当前元素及其左右元素的z-index加1
Copy after login

Bind touch events

touchstart event

When the finger is pressed, the initial position is saved

_container.addEventListener("touchstart", function(e) {
  // e.preventDefault();//取消此行代码的注释会在该元素内阻止页面纵向滚动
  var touch = e.touches[0];
  startX = touch.clientX;   //保存手指按下时的位置
  startY = touch.clientY;
  _container.style.webkitTransition = ""; //取消动画效果
  startT = new Date().getTime();          //记录手指按下的开始时间
  isMove = false;
  transitionItems(_prev, false);             //取消之前元素的过渡
  transitionItems(_current, false);          //取消当前元素的过渡
}, false);
Copy after login

touchmove event

The finger slides on the screen, and the page moves with the finger

_container.addEventListener("touchmove", function(e) {
    // e.preventDefault();//取消此行代码的注释会在该元素内阻止页面纵向滚动
    var touch = e.touches[0];
    var deltaX = touch.clientX - startX;  //计算手指在X方向滑动的距离
    var deltaY = touch.clientY - startY;  //计算手指在Y方向滑动的距离
    //如果X方向上的位移大于Y方向,则认为是左右滑动
    if (Math.abs(deltaX) > Math.abs(deltaY)){
        translate = deltaX > _itemWidth ? _itemWidth : deltaX;
        translate = deltaX < -_itemWidth ? -_itemWidth : deltaX;

        //同时移动当前元素及其左右元素
        moveItems(translate); 

        isMove = true;
    }
}, false);
Copy after login

touchend event

When the finger leaves the screen, calculate which page it needs to end up on

_container.addEventListener("touchend",function(e) {
    // e.preventDefault();//取消此行代码的注释会在该元素内阻止页面纵向滚动

    //是否会滚
    var isRollback = false;

    //计算手指在屏幕上停留的时间
    var deltaT = new Date().getTime() - startT;
    if (isMove) { //发生了左右滑动
        //如果停留时间小于300ms,则认为是快速滑动,无论滑动距离是多少,都停留到下一页
        if(deltaT < 300){
            translate = translate < 0 ? -_itemWidth : _itemWidth;
        }else {
            //如果滑动距离小于屏幕的50%,则退回到上一页
            if (Math.abs(translate) / _itemWidth < 0.5){
                isRollback = true;
            }else{
                //如果滑动距离大于屏幕的50%,则滑动到下一页
                translate = translate < 0 ? -_itemWidth : _itemWidth;
            }
        }

        moveTo(translate, isRollback);
    }
}, false);
Copy after login

Carousel library

For ease of use, I encapsulated the entire implementation process into a library and added

prev()

, next() methods are very simple to use:

<script src="lib/carousel.js"></script>

CreateCarousel("carousel", "item", true)
  .bindTouchEvent()
  .setItemChangedHandler(onPageChanged);

//参数"carousel"为容器的类名
//参数"item"为子元素的类名
//第三个参数设置是否需要循环播放,true为循环播放
Copy after login
This library can be downloaded from github

Reference

H5 single page gesture sliding screen switching principle

good night!

【Related recommendations】

1.

Free h5 online video tutorial

2.

HTML5 full version manual

3.

php.cn original html5 video tutorial

The above is the detailed content of An example tutorial on implementing a carousel (touch screen version) using H5. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

SVM examples in Python SVM examples in Python Jun 11, 2023 pm 08:42 PM

Support Vector Machine (SVM) in Python is a powerful supervised learning algorithm that can be used to solve classification and regression problems. SVM performs well when dealing with high-dimensional data and non-linear problems, and is widely used in data mining, image classification, text classification, bioinformatics and other fields. In this article, we will introduce an example of using SVM for classification in Python. We will use the SVM model from the scikit-learn library

What does h5 mean? What does h5 mean? Aug 02, 2023 pm 01:52 PM

H5 refers to HTML5, the latest version of HTML. H5 is a powerful markup language that provides developers with more choices and creative space. Its emergence promotes the development of Web technology, making the interaction and effect of web pages more Excellent, as H5 technology gradually matures and becomes popular, I believe it will play an increasingly important role in the Internet world.

How to distinguish between H5, WEB front-end, big front-end, and WEB full stack? How to distinguish between H5, WEB front-end, big front-end, and WEB full stack? Aug 03, 2022 pm 04:00 PM

This article will help you quickly distinguish between H5, WEB front-end, large front-end, and WEB full stack. I hope it will be helpful to friends in need!

VUE3 Getting Started Example: Making a Simple Video Player VUE3 Getting Started Example: Making a Simple Video Player Jun 15, 2023 pm 09:42 PM

As the new generation of front-end frameworks continues to emerge, VUE3 is loved as a fast, flexible, and easy-to-use front-end framework. Next, let's learn the basics of VUE3 and make a simple video player. 1. Install VUE3 First, we need to install VUE3 locally. Open the command line tool and execute the following command: npminstallvue@next Then, create a new HTML file and introduce VUE3: &lt;!doctypehtml&gt;

Learn best practice examples of pointer conversion in Golang Learn best practice examples of pointer conversion in Golang Feb 24, 2024 pm 03:51 PM

Golang is a powerful and efficient programming language that can be used to develop various applications and services. In Golang, pointers are a very important concept, which can help us operate data more flexibly and efficiently. Pointer conversion refers to the process of pointer operations between different types. This article will use specific examples to learn the best practices of pointer conversion in Golang. 1. Basic concepts In Golang, each variable has an address, and the address is the location of the variable in memory.

PHP simple web crawler development example PHP simple web crawler development example Jun 13, 2023 pm 06:54 PM

With the rapid development of the Internet, data has become one of the most important resources in today's information age. As a technology that automatically obtains and processes network data, web crawlers are attracting more and more attention and application. This article will introduce how to use PHP to develop a simple web crawler and realize the function of automatically obtaining network data. 1. Overview of Web Crawler Web crawler is a technology that automatically obtains and processes network resources. Its main working process is to simulate browser behavior, automatically access specified URL addresses and extract all information.

VAE algorithm example in Python VAE algorithm example in Python Jun 11, 2023 pm 07:58 PM

VAE is a generative model, its full name is VariationalAutoencoder, which is translated into Chinese as variational autoencoder. It is an unsupervised learning algorithm that can be used to generate new data, such as images, audio, text, etc. Compared with ordinary autoencoders, VAEs are more flexible and powerful and can generate more complex and realistic data. Python is one of the most widely used programming languages ​​and one of the main tools for deep learning. In Python, there are many excellent machine learning and deep

How to implement h5 to slide up on the web side to load the next page How to implement h5 to slide up on the web side to load the next page Mar 11, 2024 am 10:26 AM

Implementation steps: 1. Monitor the scroll event of the page; 2. Determine whether the page has scrolled to the bottom; 3. Load the next page of data; 4. Update the page scroll position.

See all articles