


How to implement Touch carousel on mobile terminal using native js (code example)
The content of this article is about the method (code example) of implementing the Touch carousel on the mobile terminal with native js. It has certain reference value. Friends in need can refer to it. I hope it will be useful to you. Helps.
Touch carousel
Touch carousel is actually to switch the carousel left and right by sliding your finger. Let’s use a case to show Implement it.1. html structure
Structurally, ul and li are still used to store carousel images, and ol and li are used to store carousel dots:
2. Style initialization
Some tags in html will have some default styles. For example, the body tag has a margin by default. In order not to affect the appearance, we Need to be cleared./* 清除标签默认边距 */ body,ul,li,ol,img { margin: 0; padding: 0; } /* 清除 ul 等标签前面的“小圆点” */ ul,li,ol { list-style-type: none; } /* 图片自适应 */ img { width: 100%; height: auto; border: none; /* ie8 */ display: block; -ms-interpolation-mode: bicubic; /*为了照顾ie图片缩放失真*/ }
3. Add style
When we talked about special effects earlier, we talked about how to use native js to move a wheel The concept of broadcasting pictures, but the method at that time was through li floating. Here I will introduce a new method to you - positioning.Idea:
Give the outer box of ul a relative positioning;
The height of ul here cannot be Written to death, it should be the height of the li, but due to the absolute positioning of the li, there is no way to expand this height, so the height of the ul here needs to be dynamically set in js;
give Set the relative positioning of li, and both left and top are 0. Then add a transform:translateX(300%) attribute to li. The purpose is to initialize the displayed image to be empty, and then you only need to dynamically set the translateX value of each li in js. , you can achieve carousel;
Set the small dot area, because the number of small dots is unknown, so the width of ol is also unknown, and you want to center a box with an unknown width horizontally , can be achieved using absolute positioning combined with left percentage;
Set a width and height for the li below ol, add a rounded border attribute, and float it left, so that a row of empty spaces can be displayed The little dots of the heart;
Finally, add a style class and set a background attribute in it to display the small dots corresponding to the currently displayed image.
/* 轮播图最外层盒子 */ .carousel { position: relative; overflow: hidden; } .carousel ul { /* 这个高度需要在JS里面动态添加 */ } .carousel ul li { position: absolute; width: 100%; left: 0; top: 0; /* 使用 transform:translaX(300%) 暂时将 li 移动到屏幕外面去*/ -webkit-transform: translateX(300%); transform: translateX(300%); } /* 小圆点盒子 */ .carousel .points { /* 未知宽度的盒子,使用 absolute 定位,结合 transform 的方式进行居中 */ position: absolute; left: 50%; bottom: 10px; transform: translateX(-50%); } /* 小圆点 */ .carousel .points li { width: 5px; height: 5px; border-radius: 50%; border: 1px solid #fff; float: left; margin: 0 2px; } /* 选中小圆点的样式类 */ .carousel .points li.active { background-color: #fff; }
4. js preparation
Don’t think about anything else first , when js is initialized, the first thing to do is to add a height to ul, otherwise the picture will not be displayed.
Dynamicly set the height of UL
Dynamicly generate small dots (create the number of small dots based on the number of pictures, i=0 Add active)
Initialize the basic positions of the three li
Define three variables to store the bottom (left) of the three li's Store the subscript of the last picture, center and right store the subscripts of the first and second pictures respectively)
Set the left direction position of the three li after positioning through array [subscript]
var carousel = document.querySelector('.carousel'); var carouselUl = carousel.querySelector('ul'); var carouselLis = carouselUl.querySelectorAll('li'); var points = carousel.querySelector('ol'); // 屏幕的宽度(轮播图显示区域的宽度) var screenWidth = document.documentElement.offsetWidth; // 1- ul设置高度 carouselUl.style.height = carouselLis[0].offsetHeight + 'px'; // 2- 生成小圆点 for(var i = 0; i <p><span class="img-wrap"><img src="/static/imghwm/default1.png" data-src="https://img.php.cn//upload/image/521/560/998/1546825265921477.jpg?x-oss-process=image/resize,p_40" class="lazy" title="1546825265921477.jpg" alt="How to implement Touch carousel on mobile terminal using native js (code example)"></span></p><p><strong>Rendering: </strong></p><p><span class="img-wrap"><img src="/static/imghwm/default1.png" data-src="https://img.php.cn//upload/image/167/926/523/1546825280766035.jpg?x-oss-process=image/resize,p_40" class="lazy" title="1546825280766035.jpg" alt="How to implement Touch carousel on mobile terminal using native js (code example)"></span></p><p><strong>5. Add a timer to make the pictures move</strong></p>The carousel pictures will rotate by themselves, so you need to use a timer to execute the rotation function every once in a while.
Add a timer and rotate the subscript in the timer
Extreme value judgment
Set transition (substitute The one does not require transition)
Return
Small dot focus linkage
var timer = null; // 调用定时器 timer = setInterval(showNext, 2000); // 轮播图片切换 function showNext(){ // 轮转下标 left = center; center = right; right++; // 极值判断 if(right > carouselLis.length - 1){ right = 0; } //添加过渡 carouselLis[left].style.transition = 'transform 1s'; carouselLis[center].style.transition = 'transform 1s'; // 右边的图片永远是替补的,不能添加过渡 carouselLis[right].style.transition = 'none'; // 归位 carouselLis[left].style.transform = 'translateX('+ (-screenWidth) +'px)'; carouselLis[center].style.transform = 'translateX(0px)'; carouselLis[right].style.transform = 'translateX('+ screenWidth +'px)'; // 自动设置小圆点 setPoint(); } // 动态设置小圆点的active类 var pointsLis = points.querySelectorAll('li'); function setPoint(){ for(var i = 0; i <p><span class="img-wrap"><img src="/static/imghwm/default1.png" data-src="https://img.php.cn//upload/image/882/887/928/1546825314424596.jpg?x-oss-process=image/resize,p_40" class="lazy" title="1546825314424596.jpg" alt="How to implement Touch carousel on mobile terminal using native js (code example)"></span></p><p><strong>Rendering: </strong></p><p><span class="img-wrap"><img src="/static/imghwm/default1.png" data-src="https://img.php.cn//upload/image/131/668/141/1546825350370455.gif?x-oss-process=image/resize,p_40" class="lazy" title="1546825350370455.gif" alt="How to implement Touch carousel on mobile terminal using native js (code example)"></span></p><p>##6 . touch sliding <strong></strong></p>
- The carousel image on the mobile terminal, combined with the touch sliding event, makes the effect more friendly.
- Bind three touch events respectively
touchend里面判断是否滑动成功,滑动的依据是滑动的距离(绝对值)
超过屏幕的三分之一或者滑动的时间小于300毫秒同时距离大于30(防止点击就跑)的时候都认为是滑动成功
在滑动成功的条件分支里面在判断滑动的方向,根据方向选择调用上一张还是下一张的逻辑
在滑动失败的条件分支里面添加上过渡,重新进行归位
重启定时器
var carousel = document.querySelector('.carousel'); var carouselUl = carousel.querySelector('ul'); var carouselLis = carouselUl.querySelectorAll('li'); var points = carousel.querySelector('ol'); // 屏幕的宽度 var screenWidth = document.documentElement.offsetWidth; var timer = null; // 设置 ul 的高度 carouselUl.style.height = carouselLis[0].offsetHeight + 'px'; // 动态生成小圆点 for (var i = 0; i carouselLis.length - 1) { right = 0; } //添加过渡(多次使用,封装成函数) setTransition(1, 1, 0); // 归位 setTransform(); // 自动设置小圆点 setPoint(); } // 轮播图片切换上一张 function showPrev() { // 轮转下标 right = center; center = left; left--; // 极值判断 if (left screenWidth / 3 || (dTime 30)) { // 滑动成功了 // 判断用户是往哪个方向滑 if (dx > 0) { // 往右滑 看到上一张 showPrev(); } else { // 往左滑 看到下一张 showNext(); } } else { // 添加上过渡 setTransition(1, 1, 1); // 滑动失败了 setTransform(); } // 重新启动定时器 clearInterval(timer); // 调用定时器 timer = setInterval(showNext, 2000); } // 设置过渡 function setTransition(a, b, c) { if (a) { carouselLis[left].style.transition = 'transform 1s'; } else { carouselLis[left].style.transition = 'none'; } if (b) { carouselLis[center].style.transition = 'transform 1s'; } else { carouselLis[center].style.transition = 'none'; } if (c) { carouselLis[right].style.transition = 'transform 1s'; } else { carouselLis[right].style.transition = 'none'; } } // 封装归位 function setTransform(dx) { dx = dx || 0; carouselLis[left].style.transform = 'translateX(' + (-screenWidth + dx) + 'px)'; carouselLis[center].style.transform = 'translateX(' + dx + 'px)'; carouselLis[right].style.transform = 'translateX(' + (screenWidth + dx) + 'px)'; } // 动态设置小圆点的active类 var pointsLis = points.querySelectorAll('li'); function setPoint() { for (var i = 0; i <p><span class="img-wrap"><img src="/static/imghwm/default1.png" data-src="https://img.php.cn//upload/image/613/478/733/1546825414662137.jpg?x-oss-process=image/resize,p_40" class="lazy" title="1546825414662137.jpg" alt="How to implement Touch carousel on mobile terminal using native js (code example)"></span></p><p><strong>效果图:</strong></p><p><span class="img-wrap"><img src="/static/imghwm/default1.png" data-src="https://img.php.cn//upload/image/113/780/418/1546825434914550.gif?x-oss-process=image/resize,p_40" class="lazy" title="1546825434914550.gif" alt="How to implement Touch carousel on mobile terminal using native js (code example)"></span></p>
The above is the detailed content of How to implement Touch carousel on mobile terminal using native js (code example). For more information, please follow other related articles on the PHP Chinese website!

Python is more suitable for beginners, with a smooth learning curve and concise syntax; JavaScript is suitable for front-end development, with a steep learning curve and flexible syntax. 1. Python syntax is intuitive and suitable for data science and back-end development. 2. JavaScript is flexible and widely used in front-end and server-side programming.

Python and JavaScript have their own advantages and disadvantages in terms of community, libraries and resources. 1) The Python community is friendly and suitable for beginners, but the front-end development resources are not as rich as JavaScript. 2) Python is powerful in data science and machine learning libraries, while JavaScript is better in front-end development libraries and frameworks. 3) Both have rich learning resources, but Python is suitable for starting with official documents, while JavaScript is better with MDNWebDocs. The choice should be based on project needs and personal interests.

The shift from C/C to JavaScript requires adapting to dynamic typing, garbage collection and asynchronous programming. 1) C/C is a statically typed language that requires manual memory management, while JavaScript is dynamically typed and garbage collection is automatically processed. 2) C/C needs to be compiled into machine code, while JavaScript is an interpreted language. 3) JavaScript introduces concepts such as closures, prototype chains and Promise, which enhances flexibility and asynchronous programming capabilities.

Different JavaScript engines have different effects when parsing and executing JavaScript code, because the implementation principles and optimization strategies of each engine differ. 1. Lexical analysis: convert source code into lexical unit. 2. Grammar analysis: Generate an abstract syntax tree. 3. Optimization and compilation: Generate machine code through the JIT compiler. 4. Execute: Run the machine code. V8 engine optimizes through instant compilation and hidden class, SpiderMonkey uses a type inference system, resulting in different performance performance on the same code.

JavaScript's applications in the real world include server-side programming, mobile application development and Internet of Things control: 1. Server-side programming is realized through Node.js, suitable for high concurrent request processing. 2. Mobile application development is carried out through ReactNative and supports cross-platform deployment. 3. Used for IoT device control through Johnny-Five library, suitable for hardware interaction.

I built a functional multi-tenant SaaS application (an EdTech app) with your everyday tech tool and you can do the same. First, what’s a multi-tenant SaaS application? Multi-tenant SaaS applications let you serve multiple customers from a sing

This article demonstrates frontend integration with a backend secured by Permit, building a functional EdTech SaaS application using Next.js. The frontend fetches user permissions to control UI visibility and ensures API requests adhere to role-base

JavaScript is the core language of modern web development and is widely used for its diversity and flexibility. 1) Front-end development: build dynamic web pages and single-page applications through DOM operations and modern frameworks (such as React, Vue.js, Angular). 2) Server-side development: Node.js uses a non-blocking I/O model to handle high concurrency and real-time applications. 3) Mobile and desktop application development: cross-platform development is realized through ReactNative and Electron to improve development efficiency.


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

WebStorm Mac version
Useful JavaScript development tools

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

VSCode Windows 64-bit Download
A free and powerful IDE editor launched by Microsoft

SublimeText3 Chinese version
Chinese version, very easy to use

Atom editor mac version download
The most popular open source editor