Web Front-end
JS Tutorial
How to implement Touch carousel on mobile terminal in js? (code example)How to implement Touch carousel on mobile terminal in js? (code example)
The content of this article is to introduce the method of realizing the Touch carousel chart on the mobile terminal with js. It has certain reference value. Friends in need can refer to it. I hope it will be helpful to you.
Touch carousel chart
touchThe carousel chart actually switches the carousel chart left and right by sliding your finger. Below we will use a case to implement it.
1. html structure
Structurally, we still useul,lito store carousel images,ol,lito store carousel dots:
2. Some tags of style initialization
html, there will be some default styles. For example, thebodytag has a margin by default. In order not to affect the appearance, we need to clear it out.
/* 清除标签默认边距 */
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 nativejsto move a wheel The concept of broadcasting pictures, but the method at that time was to float throughli. Here I would like to introduce a new method to you - positioning.
Idea:
Give
ulthe outer box a relative positioning;The height of
ulhere cannot be hard-coded. It should be the height ofli, but due to the absolute positioning ofli, there is no way to expand this. Height, soulhere needs to dynamically set the height injs;sets relative positioning for
li, Andleft,topare both0, and then add atransform:translateX(300%)toliAttribute, the purpose is to initialize the displayed image to be empty, and then only need to dynamically set thetranslateXvalue of eachliinjsto achieve carousel;Set the small dot area. Because the number of small dots is unknown, the width of
olis also unknown. If you want to center a box with an unknown width horizontally, It can be achieved by usingabsolutepositioning combined withleftpercentage;gives
olthe followingliSet a width and height and add a rounded border attribute, and float it to the left, so that a row of hollow dots can be displayed;Finally, add a style class inside Set a background attribute 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 work
Don’t consider anything else first,jsduring initialization , the first thing to do is to add a height toul, otherwise the picture will not be displayed.
Dynamically set the height for
ULDynamically generate small dots (create small dots based on the number of pictures Number,
i=0Addactive)Initialize the basic positions of three
liDefine three variables, which are used to store the subscripts of three
li(leftstores the subscript of the last picture,centerandrightstore the subscripts of the first and second pictures respectively)through
array [subscript]The way to set the position of the threeliin theleftdirection
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 style="text-align: center;"><img src="https://img.php.cn//upload/image/588/479/428/How%20to%20implement%20Touch%20carousel%20on%20mobile%20terminal%20in%20js?%20(code%20example)?x-oss-process=image/resize,p_40" title="How to implement Touch carousel on mobile terminal in js? (code example)" alt="How to implement Touch carousel on mobile terminal in js? (code example)" style="max-width:90%" style="max-width:90%"></p><p>##Rendering: <strong></strong></p><p style="text-align: center;"><img src="https://img.php.cn//upload/image/609/739/253/How%20to%20implement%20Touch%20carousel%20on%20mobile%20terminal%20in%20js?%20(code%20example)?x-oss-process=image/resize,p_40" title="How to implement Touch carousel on mobile terminal in js? (code example)" alt="How to implement Touch carousel on mobile terminal in js? (code example)" style="max-width:90%" style="max-width:90%"></p>5. Add a timer to make the pictures move<h3></h3>The carousel pictures will rotate by themselves, so you need Use a timer to execute a rotation function every once in a while. <blockquote></blockquote>
- Add a timer and rotate the subscript in the timer
- Extreme value judgment
- Settings Transition (the substitute does not need to 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 style="text-align: center;"><img src="https://img.php.cn//upload/image/903/520/594/How%20to%20implement%20Touch%20carousel%20on%20mobile%20terminal%20in%20js?%20(code%20example)?x-oss-process=image/resize,p_40" title="How to implement Touch carousel on mobile terminal in js? (code example)" alt="How to implement Touch carousel on mobile terminal in js? (code example)" style="max-width:90%" style="max-width:90%"></p><p>Rendering: <strong></strong></p><p style="text-align: center;"><img src="https://img.php.cn//upload/image/742/369/156/How%20to%20implement%20Touch%20carousel%20on%20mobile%20terminal%20in%20js?%20(code%20example)?x-oss-process=image/resize,p_40" title="How to implement Touch carousel on mobile terminal in js? (code example)" alt="How to implement Touch carousel on mobile terminal in js? (code example)" style="max-width:90%" style="max-width:90%"></p><h3 id="touch-滑动">6. touch 滑动</h3><blockquote>移动端的轮播图,配合<code>touch</code>滑动事件,效果更加友好。</blockquote>
分别绑定三个
touch事件touchstart里面记录手指的位置,清除定时器,记录时间touchmove里面获取差值,同时清除过渡,累加上差值的值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 style="text-align: center;"><img src="https://img.php.cn//upload/image/632/309/128/How%20to%20implement%20Touch%20carousel%20on%20mobile%20terminal%20in%20js?%20(code%20example)?x-oss-process=image/resize,p_40" title="How to implement Touch carousel on mobile terminal in js? (code example)" alt="How to implement Touch carousel on mobile terminal in js? (code example)" style="max-width:90%" style="max-width:90%"></p><p><strong>效果图:</strong></p><p style="text-align: center;"><img src="https://img.php.cn//upload/image/837/946/969/How%20to%20implement%20Touch%20carousel%20on%20mobile%20terminal%20in%20js?%20(code%20example)?x-oss-process=image/resize,p_40" title="How to implement Touch carousel on mobile terminal in js? (code example)" alt="How to implement Touch carousel on mobile terminal in js? (code example)" style="max-width:90%" style="max-width:90%"></p><p>以上就是本篇文章的全部内容,希望能对大家的学习有所帮助。更多精彩内容大家可以关注php中文网相关教程栏目!!!</p>The above is the detailed content of How to implement Touch carousel on mobile terminal in js? (code example). For more information, please follow other related articles on the PHP Chinese website!
Python vs. JavaScript: Community, Libraries, and ResourcesApr 15, 2025 am 12:16 AMPython 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.
From C/C to JavaScript: How It All WorksApr 14, 2025 am 12:05 AMThe 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.
JavaScript Engines: Comparing ImplementationsApr 13, 2025 am 12:05 AMDifferent 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.
Beyond the Browser: JavaScript in the Real WorldApr 12, 2025 am 12:06 AMJavaScript'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.
Building a Multi-Tenant SaaS Application with Next.js (Backend Integration)Apr 11, 2025 am 08:23 AMI 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
How to Build a Multi-Tenant SaaS Application with Next.js (Frontend Integration)Apr 11, 2025 am 08:22 AMThis 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: Exploring the Versatility of a Web LanguageApr 11, 2025 am 12:01 AMJavaScript 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.
The Evolution of JavaScript: Current Trends and Future ProspectsApr 10, 2025 am 09:33 AMThe latest trends in JavaScript include the rise of TypeScript, the popularity of modern frameworks and libraries, and the application of WebAssembly. Future prospects cover more powerful type systems, the development of server-side JavaScript, the expansion of artificial intelligence and machine learning, and the potential of IoT and edge computing.


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

SecLists
SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

Atom editor mac version download
The most popular open source editor

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

mPDF
mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

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






