


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:
Supports circular sliding
The width can be set arbitrarily and does not need to be the same width as the screen
The page can be scrolled vertically
The switching of callback listening elements can be set
Pure js, without any third-party library
Principle
Assumption of child elements
The
widthof .item
is 375px, use absolute positioning to place all child elements within the parent elementPlace the parent element
.carousel## The
widthis set to 375px, which is the same width as the child element
.item- is added to the parent element
.carousel
Touch events:
touchstart,
touchmove,
touchend - When the finger is pressed, the initial position is saved (
clientX
)
- When the finger slides, the sliding direction is judged by the sliding distance:
- 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
- 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
- When the finger is lifted, the sliding distance is used to determine whether to switch to the next page
- 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.
- The movement distance exceeds 50% of the width of the child element and switches the current element to the next element.
- Set the
transform
attribute of the current element to
translate3d(0px, 0px, 0px)and change
z-indexAttribute+1
- Set the
transform
attribute of the next child element to
translate3d(375px, 0px, 0px), and
z-indexAttribute+1
- Set the
transform
attribute of the previous child element to
translate3d(-375px, 0px, 0px), and set the
z-indexattribute +1
- and set the
z-index
attribute of all other child elements to Default value
- 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
First implement a doubly linked list to maintain the elements in the carousel component.
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;'><script src="lib/carousel.js"></script>
CreateCarousel("carousel", "item", true)
.bindTouchEvent()
.setItemChangedHandler(onPageChanged);
//参数"carousel"为容器的类名
//参数"item"为子元素的类名
//第三个参数设置是否需要循环播放,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 tutorialHTML5 full version manualphp.cn original html5 video tutorialThe 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!

Python中的支持向量机(SupportVectorMachine,SVM)是一个强大的有监督学习算法,可以用来解决分类和回归问题。SVM在处理高维度数据和非线性问题的时候表现出色,被广泛地应用于数据挖掘、图像分类、文本分类、生物信息学等领域。在本文中,我们将介绍在Python中使用SVM进行分类的实例。我们将使用scikit-learn库中的SVM模

H5是指HTML5,是HTML的最新版本,H5是一个功能强大的标记语言,为开发者提供了更多的选择和创造空间,它的出现推动了Web技术的发展,使得网页的交互和效果更加出色,随着H5技术的逐渐成熟和普及,相信它将会在互联网的世界中发挥越来越重要的作用。

随着互联网的普及,验证码已经成为了登录、注册、找回密码等操作的必要流程。在Gin框架中,实现验证码功能也变得异常简单。本文将介绍如何在Gin框架中使用第三方库实现验证码功能,并提供示例代码供读者参考。一、安装依赖库在使用验证码之前,我们需要安装一个第三方库goCaptcha。安装goCaptcha可以使用goget命令:$goget-ugithub

随着新一代前端框架的不断涌现,VUE3作为一个快速、灵活、易上手的前端框架备受热爱。接下来,我们就来一起学习VUE3的基础知识,制作一个简单的视频播放器。一、安装VUE3首先,我们需要在本地安装VUE3。打开命令行工具,执行以下命令:npminstallvue@next接着,新建一个HTML文件,引入VUE3:<!doctypehtml>

在H5中使用position属性可以通过CSS来控制元素的定位方式:1、相对定位relative,语法为“style="position: relative;”;2、绝对定位absolute,语法为“style="position: absolute;”;3、固定定位fixed,语法为“style="position: fixed;”等等。

VAE是一种生成模型,全称是VariationalAutoencoder,中文译作变分自编码器。它是一种无监督的学习算法,可以用来生成新的数据,比如图像、音频、文本等。与普通的自编码器相比,VAE更加灵活和强大,能够生成更加复杂和真实的数据。Python是目前使用最广泛的编程语言之一,也是深度学习的主要工具之一。在Python中,有许多优秀的机器学习和深度


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

ZendStudio 13.5.1 Mac
Powerful PHP integrated development environment

SAP NetWeaver Server Adapter for Eclipse
Integrate Eclipse with SAP NetWeaver application server.

EditPlus Chinese cracked version
Small size, syntax highlighting, does not support code prompt function

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

Atom editor mac version download
The most popular open source editor
