Written in front
Following the previous research on mobile effects, this time let’s take a look at How to implement Picke in mobile effects
The implementation principle of the selector
Swiper of mobile effects
See the code here: github
<!-- 说明: 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>1.2 Initializing DOMBecause 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('#wrapper'); var animationFrameId = null; var currentValue; var itemHeight = 36; var visibleItemCount = 3; var valueIndex = 0; var rotateEffect = true; var datas = ['1981', '1982', '1983', '...', '1999'];// 如果支持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('.How to implement Picke in mobile effects'); var How to implement Picke in mobile effectsSlot = document.querySelector('.How to implement Picke in mobile effects-slot'); How to implement Picke in mobile effects.classList.add('How to implement Picke in mobile effects-3d'); How to implement Picke in mobile effectsSlot.classList.add('How to implement Picke in mobile effects-slot-absolute');}// 限定容器高度el.style.height = `${visibleItemCount * itemHeight}px`;// 生成DOMvar html = '';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('.How to implement Picke in mobile effects-item');How to implement Picke in mobile effectsItems[valueIndex].classList.add('How to implement Picke in mobile effects-selected');
1.3 Initialization event
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 thePC terminal, and eliminates the impact of dragging and selection. Let’s take a closer look at the analysis. `
/** * draggable.js * 只是起到一定的兼容性 * 实质和直接调用 el.addEventListener('touchstart', startFn); 并没有多大差别 */// 滑动开始// touchstart 和 mousedown 可见对PC端的兼容// onselectstart/ondragstart 直接return 可见排除了拖动和选择element.addEventListener(supportTouch ? 'touchstart' : 'mousedown', function(event) { if (isDragging) return; document.onselectstart = function() { return false; }; document.ondragstart = function() { return false; }; // ...});// 滑动结束var endFn = function(event) { // 注销事件 if (!supportTouch) { document.removeEventListener('mousemove', moveFn); document.removeEventListener('mouseup', endFn); } document.onselectstart = null; document.ondragstart = null; isDragging = false; if (options.end) { options.end(supportTouch ? event.changedTouches[0] || event.touches[0] : event); }}
If
DOM
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 };}
There are two methods, the first
getDragRange
getElementTranslate(el ).
- 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
The second function is to obtain the. 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.
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
translatevalue 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) === '[object Opera]') { engine = 'presto';} else if ('MozAppearance' in docStyle) { engine = 'gecko';} else if ('WebkitAppearance' in docStyle) { engine = 'webkit';} else if (typeof navigator.cpuClass === 'string') { engine = 'trident';}// css前缀var cssPrefix = { trident: '-ms-', // IE gecko: '-moz-', // FireFox webkit: '-webkit-', // Chrome/Safari/etc... presto: '-o-' // Opera}[engine];// style前缀var vendorPrefix = { trident: 'ms', gecko: 'Moz', webkit: 'Webkit', presto: 'O'}[engine];var helpElem = document.createElement('p');var perspectiveProperty = vendorPrefix + 'Perspective';var transformProperty = vendorPrefix + 'Transform';var transformStyleName = cssPrefix + 'transform';var transitionProperty = vendorPrefix + 'Transition';var transitionStyleName = cssPrefix + 'transition';var transitionEndProperty = vendorPrefix.toLowerCase() + 'TransitionEnd';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;
Next look at the sliding
drag: function(event) { // 加上 dragging 类是为了清除过渡效果,在swiper中也有同样的应用 el.classList.add('dragging'); 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); }}
See the above code There is a
velocityTranslate
end.
end: function() { // 添加过渡 el.classList.remove('dragging'); // 惯性值 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('momentumTranslate', 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 = {};}
This is the implementation process of the entire
How to implement Picke in mobile effects
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);});
sets a displacement value based on the index for each
item
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
var VISIBEL_ITEMS_ANGLE_MAP = { 3: -45, 5: -20, 7: -15};
You can see that when there are only 3 visible elements, the highlighted part is relative to the
X
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);
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
item, and we can calculate the angle based on this.
2. Summary
How to implement Picke in mobile effects
component in Ele.me. Overall, it is very similar to the sliding one inswiper 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!

Node.js excels at efficient I/O, largely thanks to streams. Streams process data incrementally, avoiding memory overload—ideal for large files, network tasks, and real-time applications. Combining streams with TypeScript's type safety creates a powe

The differences in performance and efficiency between Python and JavaScript are mainly reflected in: 1) As an interpreted language, Python runs slowly but has high development efficiency and is suitable for rapid prototype development; 2) JavaScript is limited to single thread in the browser, but multi-threading and asynchronous I/O can be used to improve performance in Node.js, and both have advantages in actual projects.

JavaScript originated in 1995 and was created by Brandon Ike, and realized the language into C. 1.C language provides high performance and system-level programming capabilities for JavaScript. 2. JavaScript's memory management and performance optimization rely on C language. 3. The cross-platform feature of C language helps JavaScript run efficiently on different operating systems.

JavaScript runs in browsers and Node.js environments and relies on the JavaScript engine to parse and execute code. 1) Generate abstract syntax tree (AST) in the parsing stage; 2) convert AST into bytecode or machine code in the compilation stage; 3) execute the compiled code in the execution stage.

The future trends of Python and JavaScript include: 1. Python will consolidate its position in the fields of scientific computing and AI, 2. JavaScript will promote the development of web technology, 3. Cross-platform development will become a hot topic, and 4. Performance optimization will be the focus. Both will continue to expand application scenarios in their respective fields and make more breakthroughs in performance.

Both Python and JavaScript's choices in development environments are important. 1) Python's development environment includes PyCharm, JupyterNotebook and Anaconda, which are suitable for data science and rapid prototyping. 2) The development environment of JavaScript includes Node.js, VSCode and Webpack, which are suitable for front-end and back-end development. Choosing the right tools according to project needs can improve development efficiency and project success rate.

Yes, the engine core of JavaScript is written in C. 1) The C language provides efficient performance and underlying control, which is suitable for the development of JavaScript engine. 2) Taking the V8 engine as an example, its core is written in C, combining the efficiency and object-oriented characteristics of C. 3) The working principle of the JavaScript engine includes parsing, compiling and execution, and the C language plays a key role in these processes.

JavaScript is at the heart of modern websites because it enhances the interactivity and dynamicity of web pages. 1) It allows to change content without refreshing the page, 2) manipulate web pages through DOMAPI, 3) support complex interactive effects such as animation and drag-and-drop, 4) optimize performance and best practices to improve user experience.


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

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

Hot Article

Hot Tools

SublimeText3 Chinese version
Chinese version, very easy to use

PhpStorm Mac version
The latest (2018.2.1) professional PHP integrated development tool

ZendStudio 13.5.1 Mac
Powerful PHP integrated development environment

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),

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