How to use Swiper on mobile
Recently, I have used Ele.me’s vue front-end component library in the mobile terminal. Because I don’t want to use it simply with components, I want to have a deeper understanding of the implementation principle. This article mainly introduces the relevant information of Swiper on mobile effects in detail. It has certain reference value. Interested friends can refer to it. I hope it can help everyone.
The code is here: poke me
1. Description
Parent container overflow:hidden;,subpagetransform:translateX(-100%);width:100%;
2. Core analysis
2.1 Page initialization
Since all pages are one screen width on the left side of the mobile phone screen, the initial situation is that no subpage can be seen in the page, so the first step should be Set the subpage that should be displayed. By default defaultIndex:0
function reInitPages() { // 得出页面是否能够被滑动 // 1. 子页面只有一个 // 2. 用户手动设置不能滑动 noDragWhenSingle = true noDrag = children.length === 1 && noDragWhenSingle; var aPages = []; var intDefaultIndex = Math.floor(defaultIndex); var defaultIndex = (intDefaultIndex >= 0 && intDefaultIndex < children.length) ? intDefaultIndex : 0; // 得到当前被激活的子页面索引 index = defaultIndex; children.forEach(function(child, index) { aPages.push(child); // 所有页面移除激活class child.classList.remove('is-active'); if (index === defaultIndex) { // 给激活的子页面加上激活class child.classList.add('is-active'); } }); pages = aPages; }
2.2 Container sliding start (onTouchStart)
at low On version android mobile phones, setting event.preventDefault() will improve performance to a certain extent, making sliding less laggy.
Pre-work:
If the user sets prevent:true, prevent the default behavior when sliding
If the user sets prevent:true With stopPropagation:true, prevent the event from propagating upward when sliding
If the animation has not ended yet, prevent sliding
Set dragging:true and the sliding starts
Set user scrolling to false
Sliding start:
Use a global object to record information, which includes :
dragState = { startTime // 开始时间 startLeft // 开始的X坐标 startTop // 开始的Y坐标(相对于整个页面viewport pageY) startTopAbsolute // 绝对Y坐标(相对于文档顶部 clientY) pageWidth // 一个页面宽度 pageHeight // 一个页面的高度 prevPage // 上一个页面 dragPage // 当前页面 nextPage // 下一个页面 };
2.3 Container sliding (onTouchMove)
Apply global dragState, record new information
dragState = { currentLeft // 开始的X坐标 currentTop // 开始的Y坐标(相对于整个页面viewport pageY) currentTopAbsolute // 绝对Y坐标(相对于文档顶部 clientY) };
Then we can calculate something through the information in the start and slide:
The horizontal displacement of the slide (offsetLeft = currentLeft - startLeft)
Slide The vertical displacement (offsetTop = currentTopAbsolute - startTopAbsolute)
Is it the user's natural scrolling? The natural scrolling here means that the user does not want to slide the swiper, but wants to slide the page
// 条件 // distanceX = Math.abs(offsetLeft); // distanceY = Math.abs(offsetTop); distanceX < 5 || ( distanceY >= 5 && distanceY >= 1.73 * distanceX )
Determine whether to move left or right (offsetLeft < 0, move left, otherwise, move right)
Reset displacement
##
// 如果存在上一个页面并且是左移 if (dragState.prevPage && towards === 'prev') { // 重置上一个页面的水平位移为 offsetLeft - dragState.pageWidth // 由于 offsetLeft 一直在变化,并且 >0 // 那么也就是说 offsetLeft - dragState.pageWidth 的值一直在变大,但是仍未负数 // 这就是为什么当连续属性存在的时候左滑会看到上一个页面会跟着滑动的原因 // 这里的 translate 方法其实很简单,在滑动的时候去除了动画效果`transition`,单纯改变位移 // 而在滑动结束的时候,加上`transition`,使得滑动到最后释放的过渡更加自然 translate(dragState.prevPage, offsetLeft - dragState.pageWidth); } // 当前页面跟着滑动 translate(dragState.dragPage, offsetLeft); // 后一个页面同理 if (dragState.nextPage && towards === 'next') { translate(dragState.nextPage, offsetLeft + dragState.pageWidth); }
swiper does not count, so some clearing operations must be done:
dragging = false; dragState = {};
Judge whether it is a tap event
// 时间小于300ms,click事件延迟300ms触发 // 水平位移和垂直位移栋小于5像素 if (dragDuration < 300) { var fireTap = Math.abs(offsetLeft) < 5 && Math.abs(offsetTop < 5); if (isNaN(offsetLeft) || isNaN(offsetTop)) { fireTap = true; } if (fireTap) { console.log('tap'); } }
Judge Direction
// 如果事件间隔小于300ms但是滑出屏幕,直接返回 if (dragDuration < 300 && dragState.currentLeft === undefined) return; // 如果事件间隔小于300ms 或者 滑动位移超过屏幕宽度 1/2, 根据位移判断方向 if (dragDuration < 300 || Math.abs(offsetLeft) > pageWidth / 2) { towards = offsetLeft < 0 ? 'next' : 'prev'; } // 如果非连续,当处于第一页,不会出现上一页,当处于最后一页,不会出现下一页 if (!continuous) { if ((index === 0 && towards === 'prev') || (index === pageCount - 1 && towards === 'next')) { towards = null; } } // 子页面数量小于2时,不执行滑动动画 if (children.length < 2) { towards = null; }
Perform animation
##
// 当没有options的时候,为自然滑动,也就是定时器滑动 function doAnimate(towards, options) { if (children.length === 0) return; if (!options && children.length < 2) return; var prevPage, nextPage, currentPage, pageWidth, offsetLeft; var pageCount = pages.length; // 定时器滑动 if (!options) { pageWidth = element.clientWidth; currentPage = pages[index]; prevPage = pages[index - 1]; nextPage = pages[index + 1]; if (continuous && pages.length > 1) { if (!prevPage) { prevPage = pages[pages.length - 1]; } if (!nextPage) { nextPage = pages[0]; } } // 计算上一页与下一页之后 // 重置位移 // 参看doOnTouchMove // 其实这里的options 传与不传也就是获取上一页信息与下一页信息 if (prevPage) { prevPage.style.display = 'block'; translate(prevPage, -pageWidth); } if (nextPage) { nextPage.style.display = 'block'; translate(nextPage, pageWidth); } } else { prevPage = options.prevPage; currentPage = options.currentPage; nextPage = options.nextPage; pageWidth = options.pageWidth; offsetLeft = options.offsetLeft; } var newIndex; var oldPage = children[index]; // 得到滑动之后的新的索引 if (towards === 'prev') { if (index > 0) { newIndex = index - 1; } if (continuous && index === 0) { newIndex = pageCount - 1; } } else if (towards === 'next') { if (index < pageCount - 1) { newIndex = index + 1; } if (continuous && index === pageCount - 1) { newIndex = 0; } } // 动画完成之后的回调 var callback = function() { // 得到滑动之后的激活页面,添加激活class // 重新赋值索引 if (newIndex !== undefined) { var newPage = children[newIndex]; oldPage.classList.remove('is-active'); newPage.classList.add('is-active'); index = newIndex } if (isDone) { end(); } if (prevPage) { prevPage.style.display = ''; } if (nextPage) { nextPage.style.display = ''; } } setTimeout(function() { // 向后滑动 if (towards === 'next') { isDone = true; before(currentPage); // 当前页执行动画,完成后执行callback translate(currentPage, -pageWidth, speed, callback); if (nextPage) { // 下一面移动视野中 translate(nextPage, 0, speed) } } else if (towards === 'prev') { isDone = true; before(currentPage); translate(currentPage, pageWidth, speed, callback); if (prevPage) { translate(prevPage, 0, speed); } } else { // 如果既不是左滑也不是右滑 isDone = true; // 当前页面依旧处于视野中 // 上一页和下一页滑出 translate(currentPage, 0, speed, callback); if (typeof offsetLeft !== 'undefined') { if (prevPage && offsetLeft > 0) { translate(prevPage, pageWidth * -1, speed); } if (nextPage && offsetLeft < 0) { translate(nextPage, pageWidth, speed); } } else { if (prevPage) { translate(prevPage, pageWidth * -1, speed); } if (nextPage) { translate(nextPage, pageWidth, speed); } } } }, 10); }
Post-work:
Clear the status information saved in a sliding cycle
##dragging = false; dragState = {};
Summary
Overall, the implementation principle is relatively simple. The initial position is recorded when sliding starts, and the pages that should be displayed between the previous and next pages are calculated; the displacement is calculated during sliding, and the next page is calculated. The displacement of one page; when the slide ends, the corresponding animation is executed based on the displacement result.
transition
is set to empty during sliding to prevent the previous page and next page from shifting unnaturally due to the transition. Add animation effects to them after sliding.Related recommendations:
Realization of the combined effect of WeChat applet tab and swiper
detailed explanation of vue swiper implementation of component development
Detailed explanation of how to use swiper
The above is the detailed content of How to use Swiper on mobile. For more information, please follow other related articles on the PHP Chinese website!

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

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics



Can the appdata folder be moved to the D drive? With the increasing popularity of computer use, more and more users' personal data and applications are stored on the computer. In Windows operating system, there is a specific folder called appdata folder, which is used to store user's application data. Many users wonder whether this folder can be moved to the D drive or other disks for data management and security considerations. In this article, we will discuss this problem and provide some solutions. First, let me

According to news on July 23, blogger Digital Chat Station broke the news that the battery capacity of Xiaomi 15 Pro has been increased to 6000mAh and supports 90W wired flash charging. This will be the Pro model with the largest battery in Xiaomi’s digital series. Digital Chat Station previously revealed that the battery of Xiaomi 15Pro has ultra-high energy density and the silicon content is much higher than that of competing products. After silicon-based batteries are tested on a large scale in 2023, second-generation silicon anode batteries have been identified as the future development direction of the industry. This year will usher in the peak of direct competition. 1. The theoretical gram capacity of silicon can reach 4200mAh/g, which is more than 10 times the gram capacity of graphite (the theoretical gram capacity of graphite is 372mAh/g). For the negative electrode, the capacity when the lithium ion insertion amount reaches the maximum is the theoretical gram capacity, which means that under the same weight

Classification and Usage Analysis of JSP Comments JSP comments are divided into two types: single-line comments: ending with, only a single line of code can be commented. Multi-line comments: starting with /* and ending with */, you can comment multiple lines of code. Single-line comment example Multi-line comment example/**This is a multi-line comment*Can comment on multiple lines of code*/Usage of JSP comments JSP comments can be used to comment JSP code to make it easier to read

Microsoft changed the name of PhoneLink to MobileDevice in the latest Windows 11 version. This change allows users to control computer access to mobile devices through prompts. This article explains how to manage settings on your computer that allow or deny access from mobile devices. This feature allows you to configure your mobile device and connect it to your computer to send and receive text messages, control mobile applications, view contacts, make phone calls, view galleries, and more. Is it a good idea to connect your phone to your PC? Connecting your phone to your Windows PC is a convenient option, making it easy to transfer functions and media. This is useful for those who need to use their computer when their mobile device is unavailable

WPS is a commonly used office software suite, and the WPS table function is widely used for data processing and calculations. In the WPS table, there is a very useful function, the DATEDIF function, which is used to calculate the time difference between two dates. The DATEDIF function is the abbreviation of the English word DateDifference. Its syntax is as follows: DATEDIF(start_date,end_date,unit) where start_date represents the starting date.

How to use the exit function in C language requires specific code examples. In C language, we often need to terminate the execution of the program early in the program, or exit the program under certain conditions. C language provides the exit() function to implement this function. This article will introduce the usage of exit() function and provide corresponding code examples. The exit() function is a standard library function in C language and is included in the header file. Its function is to terminate the execution of the program, and can take an integer

Introduction to Python functions: usage and examples of the abs function 1. Introduction to the usage of the abs function In Python, the abs function is a built-in function used to calculate the absolute value of a given value. It can accept a numeric argument and return the absolute value of that number. The basic syntax of the abs function is as follows: abs(x) where x is the numerical parameter to calculate the absolute value, which can be an integer or a floating point number. 2. Examples of abs function Below we will show the usage of abs function through some specific examples: Example 1: Calculation

Introduction to Python functions: Usage and examples of the isinstance function Python is a powerful programming language that provides many built-in functions to make programming more convenient and efficient. One of the very useful built-in functions is the isinstance() function. This article will introduce the usage and examples of the isinstance function and provide specific code examples. The isinstance() function is used to determine whether an object is an instance of a specified class or type. The syntax of this function is as follows
