Table of Contents
Written in front
How to implement Picke in mobile effects
Home Web Front-end JS Tutorial How to implement Picke in mobile effects

How to implement Picke in mobile effects

Oct 12, 2017 am 09:41 AM
accomplish method

Written in front

Following the previous research on mobile effects, this time let’s take a look at How to implement Picke in mobile effectsThe implementation principle of the selector

Swiper of mobile effects

See the code here: github

How to implement Picke in mobile effects

##1. Core analysis

1.1 Basic HTML structure


<!--     说明:    
1. 类 How to implement Picke in mobile effects-3d 是为了提供3d视角,如果不需要可以去掉    
2. 类 How to implement Picke in mobile effects-slot-absolute 在3d视角中需要加上,因为下面相对定位的 How to implement Picke in mobile effects-items 是要相对父容器进行    transform的,如果不加,就会造成位移不正确    3. DOM中所有的style样式都是在初始化的时候加上的--><p class="How to implement Picke in mobile effects How to implement Picke in mobile effects-3d">
    <p class="How to implement Picke in mobile effects-items">
        <p class="How to implement Picke in mobile effects-slot How to implement Picke in mobile effects-slot-absolute" style="flex:1;">
            <p class="How to implement Picke in mobile effects-slot-wrapper" id="wrapper" style="height: 108px;">
                <p class="How to implement Picke in mobile effects-item How to implement Picke in mobile effects-selected" style="height:36px;line-height: 36px">1981</p>
                <!-- ... -->
                <p class="How to implement Picke in mobile effects-item" style="height:36px;line-height: 36px">1999</p>
            </p>
        </p>
    </p>
    <p class="How to implement Picke in mobile effects-center-highlight" style="height:36px;margin-top:-18px;"></p></p>
Copy after login

1.2 Initializing DOM

Because the

How to implement Picke in mobile effects in the Ele.me source code is generated using the v-for instruction, Therefore, I simply use javascript to simulate the generation of DOM.

var el = document.querySelector(&#39;#wrapper&#39;);
var animationFrameId = null;
var currentValue;
var itemHeight = 36;
var visibleItemCount = 3;
var valueIndex = 0;
var rotateEffect = true;
var datas = [&#39;1981&#39;, &#39;1982&#39;, &#39;1983&#39;, &#39;...&#39;, &#39;1999&#39;];// 如果支持3d视角,则给<p class="How to implement Picke in mobile effects"></p>加上类"How to implement Picke in mobile effects-3d"// <p class="How to implement Picke in mobile effects-slot" style="flex:1;">加上类"How to implement Picke in mobile effects-slot-absolute"if (rotateEffect) {
    var How to implement Picke in mobile effects = document.querySelector(&#39;.How to implement Picke in mobile effects&#39;);
    var How to implement Picke in mobile effectsSlot = document.querySelector(&#39;.How to implement Picke in mobile effects-slot&#39;);
    How to implement Picke in mobile effects.classList.add(&#39;How to implement Picke in mobile effects-3d&#39;);
    How to implement Picke in mobile effectsSlot.classList.add(&#39;How to implement Picke in mobile effects-slot-absolute&#39;);}// 限定容器高度el.style.height = `${visibleItemCount * itemHeight}px`;// 生成DOMvar html = &#39;&#39;;datas.forEach(function(data, index) {
    html += `<p class="How to implement Picke in mobile effects-item" style="height:36px;line-height:36px;">${data}</p>`;});el.innerHTML = html;// 激活当前itemvar How to implement Picke in mobile effectsItems = document.querySelectorAll(&#39;.How to implement Picke in mobile effects-item&#39;);How to implement Picke in mobile effectsItems[valueIndex].classList.add(&#39;How to implement Picke in mobile effects-selected&#39;);
Copy after login

1.3 Initialization event

Generally speaking, the events of

How to implement Picke in mobile effects

also include sliding start, sliding, and sliding end. Because it is a mobile device after all, sliding is inevitable. This time, the sliding event is encapsulated in the source code, compatible with the

PC terminal, and eliminates the impact of dragging and selection. Let’s take a closer look at the analysis. `

/**  * draggable.js  * 只是起到一定的兼容性 * 实质和直接调用 el.addEventListener(&#39;touchstart&#39;, startFn); 并没有多大差别 */// 滑动开始// touchstart 和 mousedown 可见对PC端的兼容// onselectstart/ondragstart 直接return 可见排除了拖动和选择element.addEventListener(supportTouch ? &#39;touchstart&#39; : &#39;mousedown&#39;, function(event) {
    if (isDragging) return;
    document.onselectstart = function() { return false; };
    document.ondragstart = function() { return false; };

    // ...});// 滑动结束var endFn = function(event) {
    // 注销事件
    if (!supportTouch) {
        document.removeEventListener(&#39;mousemove&#39;, moveFn);
        document.removeEventListener(&#39;mouseup&#39;, endFn);
    }
    document.onselectstart = null;
    document.ondragstart = null;

    isDragging = false;

    if (options.end) {
        options.end(supportTouch ? event.changedTouches[0] || event.touches[0] : event);
    }}
Copy after login

If
DOM

follows your sliding on the mobile phone screen, the method is similar, it is nothing more than recording the starting position at the beginning of sliding. Calculate the displacement in real time, and after the sliding is completed,

DOM will slide to the position where it should slide. For this point, please refer to the previous article Swiper for mobile effects. This article has the same method. Here we focus on the difference

// 滑动开始的执行事件方法start: function(event) {
    dragState = {
        range: getDragRange(),
        // ...
        startTranslateTop: translateUtil.getElementTranslate(el).top
    };}
Copy after login

There are two methods, the first
getDragRange

and the second

getElementTranslate(el ).

The function of the first function is to obtain the minimum and maximum displacement that
    How to implement Picke in mobile effects
  • can slide, which will be used in the sliding end event arrive. Regarding how to calculate, here is a brief mention. When you slide down, the maximum cannot exceed the top of the middle

    item. This is why itemHeight * Math.floor(visibleItemCount / 2) , and when sliding upward, the maximum cannot exceed the bottom of the middle item, -itemHeight * (valuesLength - Math.ceil(visibleItemCount / 2)), just think about it carefully.

    The second function is to obtain the
  • transform
  • value of the current

    How to implement Picke in mobile effects as the basis for the next sliding calculation. In fact, it feels like this is quite troublesome, because the translate value will definitely be calculated in touchend. We only need to save the last sliding movement value each time, instead of doing it every time. Get it from DOM.

/** * translateUtil * 对浏览器对前缀支持的一些判断 * 检测浏览器对3d属性的支持情况 * 获取当前的translate值/清空How to implement Picke in mobile effects的translate值/移动How to implement Picke in mobile effects * 对于浏览器的检测方面,这也算是一个比较好的工具类 */var docStyle = document.documentElement.style;var engine;var translate3d = false;// 浏览器判断if (window.opera && Object.prototype.toString.call(opera) === &#39;[object Opera]&#39;) {
    engine = &#39;presto&#39;;} else if (&#39;MozAppearance&#39; in docStyle) {
    engine = &#39;gecko&#39;;} else if (&#39;WebkitAppearance&#39; in docStyle) {
    engine = &#39;webkit&#39;;} else if (typeof navigator.cpuClass === &#39;string&#39;) {
    engine = &#39;trident&#39;;}// css前缀var cssPrefix = {
    trident: &#39;-ms-&#39;,        // IE
    gecko: &#39;-moz-&#39;,         // FireFox
    webkit: &#39;-webkit-&#39;,     // Chrome/Safari/etc...
    presto: &#39;-o-&#39;           // Opera}[engine];// style前缀var vendorPrefix = {
    trident: &#39;ms&#39;,
    gecko: &#39;Moz&#39;,
    webkit: &#39;Webkit&#39;,
    presto: &#39;O&#39;}[engine];var helpElem = document.createElement(&#39;p&#39;);var perspectiveProperty = vendorPrefix + &#39;Perspective&#39;;var transformProperty = vendorPrefix + &#39;Transform&#39;;var transformStyleName = cssPrefix + &#39;transform&#39;;var transitionProperty = vendorPrefix + &#39;Transition&#39;;var transitionStyleName = cssPrefix + &#39;transition&#39;;var transitionEndProperty = vendorPrefix.toLowerCase() + &#39;TransitionEnd&#39;;if (helpElem.style[perspectiveProperty] !== undefined) {
    translate3d = true;}// 讲一下这个正则// \s*(-?\d+(\.\d+?)?)px 这是一个单元,匹配这样的 -23.15px, 剩下的应该就好理解了var regexp = /translate\(\s*(-?\d+(\.\d+?)?)px,\s*(-?\d+(\.\d+?)?)px\)\s*translateZ\(0px\)/ig;
Copy after login

Next look at the sliding

drag: function(event) {
    // 加上 dragging 类是为了清除过渡效果,在swiper中也有同样的应用
    el.classList.add(&#39;dragging&#39;);

    dragState.left = event.pageX;
    dragState.top = event.pageY;

    var deltaY = dragState.top - dragState.startTop;
  
    // 计算当前的滑动位移
    var translate = dragState.startTranslateTop + deltaY;

    // 滑动元素
    translateUtil.translateElement(el, null, translate);
    velocityTranslate = translate - prevTranslate || translate;

    prevTranslate = translate;

    if (rotateEffect) {
        updateRotate(prevTranslate, How to implement Picke in mobile effectsItems);
    }}
Copy after login

See the above code There is a
velocityTranslate

. This value has a magical effect. I didn’t know it at first. Later, I found out that it was used after the sliding was completed, and then I realized that it represents a displacement value of a velocity. What is velocity? Just like when you slide quickly, you always hope that it can slide with inertia. This value multiplied by an inertia value can get an inertial displacement. Look at the code in

end.

end: function() {
    // 添加过渡
    el.classList.remove(&#39;dragging&#39;);
    // 惯性值
    var momentumRatio = 7;
    var currentTranslate = translateUtil.getElementTranslate(el).top;
    var duration = new Date() - dragState.start;

    var momentumTranslate;
    if (duration < 300) {
        momentumTranslate = currentTranslate + velocityTranslate * momentumRatio;
    }

    // 加上惯性速率之后的位移值
    console.log(&#39;momentumTranslate&#39;, momentumTranslate);

    dragRange = dragState.range;

    setTimeout(function() {
        var translate;
        if (momentumTranslate) {
            translate = Math.round(momentumTranslate / itemHeight) * itemHeight;
        } else {
            translate = Math.round(currentTranslate / itemHeight) * itemHeight;
        }

        // 取得最终的位移值,
        // 必须为itemHeight的倍数
        // 在范围的最大值和最小值中取
        translate = Math.max(Math.min(translate, dragRange[1]), dragRange[0]);
        translateUtil.translateElement(el, null, translate);

        // 计算得出当前位移下应该对应的实际值
        currentValue = translate2Value(translate);

        // 3d效果
        if (rotateEffect) {
            planUpdateRotate();
        }
    }, 10);

    dragState = {};}
Copy after login

This is the implementation process of the entire
How to implement Picke in mobile effects

. It can be used without the

3d effect. Let’s take a look at how to achieve the 3D effect. There is an initial initialization in doOnValuesChange.

[].forEach.call(items, function(item, index) {
    translateUtil.translateElement(item, null, itemHeight * index);});
Copy after login

sets a displacement value based on the index for each
item

. At this time, the positioning of each

item is They must be absolute, so that they are next to each other after the displacement. Otherwise, there may be a space of itemHeight in the middle. 3D

The most critical point in the effect is how to calculate the flip angle. A constant object is defined in the source code:

var VISIBEL_ITEMS_ANGLE_MAP = {
    3: -45,
    5: -20,
    7: -15};
Copy after login

You can see that when there are only 3 visible elements, the highlighted part is relative to the
X

axis Parallel, the previous

item must be rotated 45 degrees clockwise around the X axis, and the next item must be rotated 45 degrees counterclockwise around the X axis Spend. In addition, there is a section of code that is particularly convoluted. According to my understanding, it is as follows:

// 当前item相对于顶部原本应该有的位移值var itemOffsetTop = index * itemHeight; // 滑动过程中,相对于最开始的位置滑动的位移值var translateOffset = dragRange[1] - currentTranslate;// 当应该有的位移值和滑动的位移值相等的时候,也就说明了当前的`item`被选中// 也就是说此时当前的角度为0var itemOffset = itemOffsetTop - translateOffset;var percentage = itemOffset / itemHeight;var angle = angleUnit * percentage;if (angle > 180) angle = 180;if (angle < -180) angle = -180;rotateElement(item, angle);
Copy after login

If you think it is too convoluted, there is actually no need to follow his approach. We only need to find a way to determine whether each
item

is in the previous or next position relative to the currently selected

item, and we can calculate the angle based on this. 2. Summary

I have read so much about the

How to implement Picke in mobile effects

component in Ele.me. Overall, it is very similar to the sliding one in

swiper Similar, the key point is to calculate the final displacement value to slide to the correct position according to the displacement value. As for how to calculate the value, in fact, everyone's implementation may be similar, and there is no need to follow the source code. You can Add your own understanding appropriately, so that you may be more comfortable writing code. This is just my personal understanding, and I hope it can provide some help to myself and everyone else.

The above is the detailed content of How to implement Picke in mobile effects. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
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

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

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How to write a novel in the Tomato Free Novel app. Share the tutorial on how to write a novel in Tomato Novel. How to write a novel in the Tomato Free Novel app. Share the tutorial on how to write a novel in Tomato Novel. Mar 28, 2024 pm 12:50 PM

Tomato Novel is a very popular novel reading software. We often have new novels and comics to read in Tomato Novel. Every novel and comic is very interesting. Many friends also want to write novels. Earn pocket money and edit the content of the novel you want to write into text. So how do we write the novel in it? My friends don’t know, so let’s go to this site together. Let’s take some time to look at an introduction to how to write a novel. Share the Tomato novel tutorial on how to write a novel. 1. First open the Tomato free novel app on your mobile phone and click on Personal Center - Writer Center. 2. Jump to the Tomato Writer Assistant page - click on Create a new book at the end of the novel.

How to enter bios on Colorful motherboard? Teach you two methods How to enter bios on Colorful motherboard? Teach you two methods Mar 13, 2024 pm 06:01 PM

Colorful motherboards enjoy high popularity and market share in the Chinese domestic market, but some users of Colorful motherboards still don’t know how to enter the bios for settings? In response to this situation, the editor has specially brought you two methods to enter the colorful motherboard bios. Come and try it! Method 1: Use the U disk startup shortcut key to directly enter the U disk installation system. The shortcut key for the Colorful motherboard to start the U disk with one click is ESC or F11. First, use Black Shark Installation Master to create a Black Shark U disk boot disk, and then turn on the computer. When you see the startup screen, continuously press the ESC or F11 key on the keyboard to enter a window for sequential selection of startup items. Move the cursor to the place where "USB" is displayed, and then

How to recover deleted contacts on WeChat (simple tutorial tells you how to recover deleted contacts) How to recover deleted contacts on WeChat (simple tutorial tells you how to recover deleted contacts) May 01, 2024 pm 12:01 PM

Unfortunately, people often delete certain contacts accidentally for some reasons. WeChat is a widely used social software. To help users solve this problem, this article will introduce how to retrieve deleted contacts in a simple way. 1. Understand the WeChat contact deletion mechanism. This provides us with the possibility to retrieve deleted contacts. The contact deletion mechanism in WeChat removes them from the address book, but does not delete them completely. 2. Use WeChat’s built-in “Contact Book Recovery” function. WeChat provides “Contact Book Recovery” to save time and energy. Users can quickly retrieve previously deleted contacts through this function. 3. Enter the WeChat settings page and click the lower right corner, open the WeChat application "Me" and click the settings icon in the upper right corner to enter the settings page.

How to set font size on mobile phone (easily adjust font size on mobile phone) How to set font size on mobile phone (easily adjust font size on mobile phone) May 07, 2024 pm 03:34 PM

Setting font size has become an important personalization requirement as mobile phones become an important tool in people's daily lives. In order to meet the needs of different users, this article will introduce how to improve the mobile phone use experience and adjust the font size of the mobile phone through simple operations. Why do you need to adjust the font size of your mobile phone - Adjusting the font size can make the text clearer and easier to read - Suitable for the reading needs of users of different ages - Convenient for users with poor vision to use the font size setting function of the mobile phone system - How to enter the system settings interface - In Find and enter the "Display" option in the settings interface - find the "Font Size" option and adjust it. Adjust the font size with a third-party application - download and install an application that supports font size adjustment - open the application and enter the relevant settings interface - according to the individual

How to implement dual WeChat login on Huawei mobile phones? How to implement dual WeChat login on Huawei mobile phones? Mar 24, 2024 am 11:27 AM

How to implement dual WeChat login on Huawei mobile phones? With the rise of social media, WeChat has become one of the indispensable communication tools in people's daily lives. However, many people may encounter a problem: logging into multiple WeChat accounts at the same time on the same mobile phone. For Huawei mobile phone users, it is not difficult to achieve dual WeChat login. This article will introduce how to achieve dual WeChat login on Huawei mobile phones. First of all, the EMUI system that comes with Huawei mobile phones provides a very convenient function - dual application opening. Through the application dual opening function, users can simultaneously

The secret of hatching mobile dragon eggs is revealed (step by step to teach you how to successfully hatch mobile dragon eggs) The secret of hatching mobile dragon eggs is revealed (step by step to teach you how to successfully hatch mobile dragon eggs) May 04, 2024 pm 06:01 PM

Mobile games have become an integral part of people's lives with the development of technology. It has attracted the attention of many players with its cute dragon egg image and interesting hatching process, and one of the games that has attracted much attention is the mobile version of Dragon Egg. To help players better cultivate and grow their own dragons in the game, this article will introduce to you how to hatch dragon eggs in the mobile version. 1. Choose the appropriate type of dragon egg. Players need to carefully choose the type of dragon egg that they like and suit themselves, based on the different types of dragon egg attributes and abilities provided in the game. 2. Upgrade the level of the incubation machine. Players need to improve the level of the incubation machine by completing tasks and collecting props. The level of the incubation machine determines the hatching speed and hatching success rate. 3. Collect the resources required for hatching. Players need to be in the game

Quickly master: How to open two WeChat accounts on Huawei mobile phones revealed! Quickly master: How to open two WeChat accounts on Huawei mobile phones revealed! Mar 23, 2024 am 10:42 AM

In today's society, mobile phones have become an indispensable part of our lives. As an important tool for our daily communication, work, and life, WeChat is often used. However, it may be necessary to separate two WeChat accounts when handling different transactions, which requires the mobile phone to support logging in to two WeChat accounts at the same time. As a well-known domestic brand, Huawei mobile phones are used by many people. So what is the method to open two WeChat accounts on Huawei mobile phones? Let’s reveal the secret of this method. First of all, you need to use two WeChat accounts at the same time on your Huawei mobile phone. The easiest way is to

PHP Programming Guide: Methods to Implement Fibonacci Sequence PHP Programming Guide: Methods to Implement Fibonacci Sequence Mar 20, 2024 pm 04:54 PM

The programming language PHP is a powerful tool for web development, capable of supporting a variety of different programming logics and algorithms. Among them, implementing the Fibonacci sequence is a common and classic programming problem. In this article, we will introduce how to use the PHP programming language to implement the Fibonacci sequence, and attach specific code examples. The Fibonacci sequence is a mathematical sequence defined as follows: the first and second elements of the sequence are 1, and starting from the third element, the value of each element is equal to the sum of the previous two elements. The first few elements of the sequence

See all articles