How to create alphabetical index navigation on the mobile terminal
This time I will show you how to make alphabetical index navigation on the mobile terminal. What are the precautions for making alphabetical index navigation on the mobile terminal. The following is a practical case, let’s take a look.
vue better-scroll implements alphabetical index navigation of the mobile singer list. It can be regarded as a study note. Write a note to let yourself understand more deeply.
Demo: list-view, use chrome mobile mode to view. After switching to mobile mode, if you can't slide, refresh it and it will be OK.
Github: Mobile alphabetical index navigation
Rendering
Configuration environment
Because vue-cli and better-scroll are used, vue-cli must be installed first, and then npm install better-scroll.
A brief introduction to better-scroll:
better-scroll is a plug-in that focuses on solving the needs of various scrolling scenarios on the mobile terminal (PC has been supported). Its core is based on the implementation of iscroll. Its API design is basically compatible with iscroll. On the basis of iscroll, it has expanded some features and made some performance optimization.
better-scroll is implemented based on native JS and does not rely on any framework. Its compiled code size is 63kb, 35kb after compression, and only 9kb after gzip. It is a very lightweight JS lib.
In addition to these two, scss and vue-lazyload are also used. Everyone knows the scss preprocessor, and it’s the same with anything else. lazyload implements lazy loading, which can be used without it. The main purpose is to optimize the experience.
The data directly uses the singer list of NetEase Cloud, and if I am lazy, I put it directly in the data.
I won’t post the CSS styles, just look at the source code.
Implement the basic style
Directly use v-for and bilateral nesting to implement the singer list and the index column on the right.
HTML structure:
<ul> <li v-for="group in singers" class="list-group" :key="group.id" ref="listGroup"> <h2 class="list-group-title">{{ group.title }}</h2> <ul> <li v-for="item in group.items" class="list-group-item" :key="item.id"> <img v-lazy="item.avatar" class="avatar"> <span class="name">{{ item.name }}</span> </li> </ul> </li> </ul> <p class="list-shortcut"> <ul> <li v-for="(item, index) in shortcutList" class="item" :data-index="index" :key="item.id" > {{ item }} </li> </ul> </p>
shortcutList is obtained by calculating attributes, just take the first character of title.
shortcutList () { return this.singers.map((group) => { return group.title.substr(0, 1) }) }
Use better-scroll
Use better-scroll to achieve scrolling. By the way, don’t forget to use import when using it.
created () { // 初始化 better-scroll 必须要等 dom 加载完毕 setTimeout(() => { this._initSrcoll() }, 20) }, methods: { _initSrcoll () { console.log('didi') this.scroll = new BScroll(this.$refs.listView, { // 获取 scroll 事件,用来监听。 probeType: 3 }) } }
Use the created method for better-scroll initialization, and use setTimeout because you need to wait until the DOM is loaded. Otherwise, better-scroll will fail to initialize if it cannot obtain the dom.
Write the method here in two methods, so that it will not look messy, just call it directly.
During initialization, two probeTypes are passed in: 3. Explain: when probeType is 3, scroll events are dispatched in real time not only during the screen sliding process, but also during the running of the momentum scrolling animation. If this value is not set, its default value is 0, which means no scroll event is dispatched.
Add click events and move events to the index to achieve jump
First you need to bind a touchstart event to the index (when pressing on the screen Triggered when you lower your finger), just use v-on. Then you need to add a data-index to the index so that you can get the index value, use :data-index="index" .
<p class="list-shortcut"> <ul> <li v-for="(item, index) in shortcutList" class="item" :data-index="index" :key="item.id" @touchstart="onShortcutStart" @touchmove.stop.prevent="onShortcutMove" > {{ item }} </li> </ul> </p>
Bind an onShortcutStart method. Implement the function of clicking the index jump. Then bind an onShortcutMove method to realize sliding jump.
created () { // 添加一个 touch 用于记录移动的属性 this.touch = {} // 初始化 better-scroll 必须要等 dom 加载完毕 setTimeout(() => { this._initSrcoll() }, 20) }, methods: { _initSrcoll () { this.scroll = new BScroll(this.$refs.listView, { probeType: 3, click: true }) }, onShortcutStart (e) { // 获取到绑定的 index let index = e.target.getAttribute('data-index') // 使用 better-scroll 的 scrollToElement 方法实现跳转 this.scroll.scrollToElement(this.$refs.listGroup[index]) // 记录一下点击时候的 Y坐标 和 index let firstTouch = e.touches[0].pageY this.touch.y1 = firstTouch this.touch.anchorIndex = index }, onShortcutMove (e) { // 再记录一下移动时候的 Y坐标,然后计算出移动了几个索引 let touchMove = e.touches[0].pageY this.touch.y2 = touchMove // 这里的 16.7 是索引元素的高度 let delta = Math.floor((this.touch.y2 - this.touch.y1) / 18) // 计算最后的位置 // * 1 是因为 this.touch.anchorIndex 是字符串,用 * 1 偷懒的转化一下 let index = this.touch.anchorIndex * 1 + delta this.scroll.scrollToElement(this.$refs.listGroup[index]) } }
In this way, the index function can be realized.
Of course this won’t satisfy us, right? We need to add cool special effects. For example, index highlighting and so on~~
Mobile content index highlighting
emmm, this time it’s a bit complicated. But you can understand it if you have patience.
We need the on method of better-scroll to return the Y-axis offset value when the content is scrolled. So you need to add some code when initializing better-scroll. By the way, don’t forget to add a scrollY in data, and currentIndex (used to record the position of the highlighted index) because we need to listen, so add it in data.
_initSrcoll () { this.scroll = new BScroll(this.$refs.listView, { probeType: 3, click: true }) // 监听Y轴偏移的值 this.scroll.on('scroll', (pos) => { this.scrollY = pos.y }) }
然后需要计算一下内容的高度,添加一个 calculateHeight() 方法,用来计算索引内容的高度。
_calculateHeight () { this.listHeight = [] const list = this.$refs.listGroup let height = 0 this.listHeight.push(height) for (let i = 0; i < list.length; i++) { let item = list[i] height += item.clientHeight this.listHeight.push(height) } } // [0, 760, 1380, 1720, 2340, 2680, 2880, 3220, 3420, 3620, 3960, 4090, 4920, 5190, 5320, 5590, 5790, 5990, 6470, 7090, 7500, 7910, 8110, 8870] // 得到这样的值
然后在 watch 中监听 scrollY,看代码:
watch: { scrollY (newVal) { // 向下滑动的时候 newVal 是一个负数,所以当 newVal > 0 时,currentIndex 直接为 0 if (newVal > 0) { this.currentIndex = 0 return } // 计算 currentIndex 的值 for (let i = 0; i < this.listHeight.length - 1; i++) { let height1 = this.listHeight[i] let height2 = this.listHeight[i + 1] if (-newVal >= height1 && -newVal < height2) { this.currentIndex = i return } } // 当超 -newVal > 最后一个高度的时候 // 因为 this.listHeight 有头尾,所以需要 - 2 this.currentIndex = this.listHeight.length - 2 } }
得到 currentIndex 的之后,在 html 中使用。
给索引绑定 class --> :class="{'current': currentIndex === index}"
最后再处理一下滑动索引的时候改变 currentIndex。
因为代码可以重复利用,且需要处理边界情况,所以就把
this.scroll.scrollToElement(this.$refs.listGroup[index])
重新写了个函数,来减少代码量。
// 在 scrollToElement 的时候,改变 scrollY,因为有 watch 所以就会计算出 currentIndex scrollToElement (index) { // 处理边界情况 // 因为 index 通过滑动距离计算出来的 // 所以向上滑超过索引框框的时候就会 < 0,向上就会超过最大值 if (index < 0) { return } else if (index > this.listHeight.length - 2) { index = this.listHeight.length - 2 } // listHeight 是正的, 所以加个 - this.scrollY = -this.listHeight[index] this.scroll.scrollToElement(this.$refs.listGroup[index]) }
lazyload
lazyload 插件也顺便说一下哈,增加一下用户体验。
使用方法
先 npm 安装
在 main.js 中 import,然后 Vue.use
import VueLazyload from 'vue-lazyload' Vue.use(VueLazyload, { loading: require('./common/image/default.jpg') })
添加一张 loading 图片,使用 webpack 的 require 获取图片。
然后在需要使用的时候,把 :src="" 换成 v-lazy="" 就实现了图片懒加载的功能。
总结
移动端字母索引导航就这么实现啦,感觉还是很有难度的哈(对我来说)。
主要就是使用了 better-scroll 的 on 获取移动偏移值(实现高亮)、scrollToElement 跳转到相应的位置(实现跳转)。以及使用 touch 事件监听触摸,来获取开始的位置,以及滑动距离(计算最后的位置)。
相信看了本文案例你已经掌握了方法,更多精彩请关注php中文网其它相关文章!
推荐阅读:
The above is the detailed content of How to create alphabetical index navigation on the mobile terminal. 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

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

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

How to Fix 100% Disk Usage on Windows 11 The straightforward way to find the problematic application or service causing 100% disk usage is to use Task Manager. To open Task Manager, right-click on the Start menu and select Task Manager. Click the Disk column header to see what's using the most resources. From there, you'll have a good idea of where to start. However, the problem may be more serious than simply closing an application or disabling a service. Read on to find more potential causes of problems and how to fix them. Disabling SuperfetchSuperfetch feature (also known as SysMain in Windows 11) helps reduce startup time by accessing prefetch files

Subtitles not working on Stremio on your Windows PC? Some Stremio users reported that subtitles were not displayed in the videos. Many users reported encountering an error message that said "Error loading subtitles." Here is the full error message that appears with this error: An error occurred while loading subtitles Failed to load subtitles: This could be a problem with the plugin you are using or your network. As the error message says, it could be your internet connection that is causing the error. So please check your network connection and make sure your internet is working properly. Apart from this, there could be other reasons behind this error, including conflicting subtitles add-on, unsupported subtitles for specific video content, and outdated Stremio app. like

If your search bar isn't working in Windows 11, there are a few quick ways to get it up and running in no time! Any Microsoft operating system can experience glitches from time to time, and the latest operating systems are not exempt from this rule. Additionally, as pointed out by user u/zebra_head1 on Reddit, the same error appears on Windows 11 with 22H2Build22621.1413. Users complained that the option to toggle the taskbar search box randomly disappeared. Therefore, you must be prepared for any situation. Why can't I type in the search bar on my computer? The inability to type on the computer can be attributed to different factors and processes. Here are some things you should be aware of: Ctfmon.

<h2>How to Hide Files and Folders from Search on Windows 11</h2><p>The first thing we need to look at is customizing the location of Windows Search files. By skipping these specific locations, you should be able to see results faster while also hiding any files you want to protect. </p><p>If you want to exclude files and folders from searches on Windows 11, use the following steps: </p><ol&

In this problem, a string is given as input and we have to sort the words appearing in the string in lexicographic order. To do this, we assign an index starting from 1 to each word in the string (separated by spaces) and get the output in the form of sorted indices. String={"Hello","World"}"Hello"=1 "World"=2 Since the words in the input string are in lexicographic order, the output will print "12". Let's look at some input/result scenarios - Assuming all words in the input string are the same, let's look at the results - Input:{"hello","hello","hello"}Result:3 Result obtained

Oracle index types include: 1. B-Tree index; 2. Bitmap index; 3. Function index; 4. Hash index; 5. Reverse key index; 6. Local index; 7. Global index; 8. Domain index ; 9. Bitmap connection index; 10. Composite index. Detailed introduction: 1. B-Tree index is a self-balancing tree data structure that can efficiently support concurrent operations. In Oracle database, B-Tree index is the most commonly used index type; 2. Bit Graph index is an index type based on bitmap algorithm and so on.

Run the Search and Indexing Troubleshooter in Outlook One of the more straightforward fixes you can start is to run the Search and Indexing Troubleshooter. To run the troubleshooter on Windows 11: Click the Start button or press the Windows key and select Settings from the menu. When Settings opens, select System > Troubleshooting > Additional Troubleshooting. Scroll down on the right side, find SearchandIndexing and click the Run button. Select Outlook Search to return no results and continue with the on-screen instructions. When you run it, the troubleshooter will automatically identify and fix the problem. After running the troubleshooter, open Outlook and see if the search is working properly. like

Golang implementation: Methods to determine whether a character is a letter In Golang, there are many ways to determine whether a character is a letter. This article will introduce several of these commonly used methods and provide specific code examples for each method. Method 1: Use the IsLetter function of the Unicode package. The Unicode package in Golang provides a function called IsLetter, which can determine whether a character is a letter. This function is used as follows: packagemaini
