search
HomeWeb Front-endH5 TutorialAn example tutorial on implementing a carousel (touch screen version) using H5

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 id="item">item-1</h3>  
  </p>  
  <p class="item" style="background: #58c03b;">    
    <h3 id="item">item-2</h3>  
  </p>  
  <p class="item" style="background: #c03b25;">    
    <h3 id="item">item-3</h3>
  </p> 
  <p class="item" style="background: #e0a718;">  
    <h3 id="item">item-4</h3>  
  </p>  
  <p class="item" style="background: #c03eac;">    
    <h3 id="item">item-5</h3>  
  </p>
</p>

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

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

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);
        }
    }
}

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

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);

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);

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);

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: <pre class='brush:php;toolbar:false;'>&lt;script src=&quot;lib/carousel.js&quot;&gt;&lt;/script&gt; CreateCarousel(&quot;carousel&quot;, &quot;item&quot;, true) .bindTouchEvent() .setItemChangedHandler(onPageChanged); //参数&quot;carousel&quot;为容器的类名 //参数&quot;item&quot;为子元素的类名 //第三个参数设置是否需要循环播放,true为循环播放</pre>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
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
Understanding H5 Code: The Fundamentals of HTML5Understanding H5 Code: The Fundamentals of HTML5Apr 17, 2025 am 12:08 AM

HTML5 is a key technology for building modern web pages, providing many new elements and features. 1. HTML5 introduces semantic elements such as, , etc., which enhances web page structure and SEO. 2. Support multimedia elements and embed media without plug-ins. 3. Forms enhance new input types and verification properties, simplifying the verification process. 4. Offer offline and local storage functions to improve web page performance and user experience.

H5 Code: Best Practices for Web DevelopersH5 Code: Best Practices for Web DevelopersApr 16, 2025 am 12:14 AM

Best practices for H5 code include: 1. Use correct DOCTYPE declarations and character encoding; 2. Use semantic tags; 3. Reduce HTTP requests; 4. Use asynchronous loading; 5. Optimize images. These practices can improve the efficiency, maintainability and user experience of web pages.

H5: The Evolution of Web Standards and TechnologiesH5: The Evolution of Web Standards and TechnologiesApr 15, 2025 am 12:12 AM

Web standards and technologies have evolved from HTML4, CSS2 and simple JavaScript to date and have undergone significant developments. 1) HTML5 introduces APIs such as Canvas and WebStorage, which enhances the complexity and interactivity of web applications. 2) CSS3 adds animation and transition functions to make the page more effective. 3) JavaScript improves development efficiency and code readability through modern syntax of Node.js and ES6, such as arrow functions and classes. These changes have promoted the development of performance optimization and best practices of web applications.

Is H5 a Shorthand for HTML5? Exploring the DetailsIs H5 a Shorthand for HTML5? Exploring the DetailsApr 14, 2025 am 12:05 AM

H5 is not just the abbreviation of HTML5, it represents a wider modern web development technology ecosystem: 1. H5 includes HTML5, CSS3, JavaScript and related APIs and technologies; 2. It provides a richer, interactive and smooth user experience, and can run seamlessly on multiple devices; 3. Using the H5 technology stack, you can create responsive web pages and complex interactive functions.

H5 and HTML5: Commonly Used Terms in Web DevelopmentH5 and HTML5: Commonly Used Terms in Web DevelopmentApr 13, 2025 am 12:01 AM

H5 and HTML5 refer to the same thing, namely HTML5. HTML5 is the fifth version of HTML, bringing new features such as semantic tags, multimedia support, canvas and graphics, offline storage and local storage, improving the expressiveness and interactivity of web pages.

What Does H5 Refer To? Exploring the ContextWhat Does H5 Refer To? Exploring the ContextApr 12, 2025 am 12:03 AM

H5referstoHTML5,apivotaltechnologyinwebdevelopment.1)HTML5introducesnewelementsandAPIsforrich,dynamicwebapplications.2)Itsupportsmultimediawithoutplugins,enhancinguserexperienceacrossdevices.3)SemanticelementsimprovecontentstructureandSEO.4)H5'srespo

H5: Tools, Frameworks, and Best PracticesH5: Tools, Frameworks, and Best PracticesApr 11, 2025 am 12:11 AM

The tools and frameworks that need to be mastered in H5 development include Vue.js, React and Webpack. 1.Vue.js is suitable for building user interfaces and supports component development. 2.React optimizes page rendering through virtual DOM, suitable for complex applications. 3.Webpack is used for module packaging and optimize resource loading.

The Legacy of HTML5: Understanding H5 in the PresentThe Legacy of HTML5: Understanding H5 in the PresentApr 10, 2025 am 09:28 AM

HTML5hassignificantlytransformedwebdevelopmentbyintroducingsemanticelements,enhancingmultimediasupport,andimprovingperformance.1)ItmadewebsitesmoreaccessibleandSEO-friendlywithsemanticelementslike,,and.2)HTML5introducednativeandtags,eliminatingthenee

See all articles

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

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Chat Commands and How to Use Them
1 months agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version