HTML结构:
<template> <div class="alphabet-container"> <h1>alphabet 组件</h1> <div @touchmove.prevent="touchMove($event)" class="letter-index"> <p @click="getLetter(item)" :ref="'ref' + item" v-for="item in alphabet" :key="item">{{item}}</p> </div> <div v-show="letterTipFlag" class="letter-tip">{{letterTipText}}</div> <ul class="alpha-index"> <li v-for="(item, index) in nameList" :key="index"> <div :id="item.alphabet">{{item.alphabet}}</div> <ul class="sub-alpha"> <li v-for="(subItem, subIndex) in item.name" :key="subIndex">{{subItem}}</li> </ul> </li> </ul> </div> </template>
JS:
export default { name: "Alphabet", data() { return { lastLetterDom: '', timer: null, letterTipText: '', letterTipFlag: false, alphabet: ["A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z"], nameList: [ { alphabet: 'A', name: ['阿花', '阿明', '阿明', '阿明', '阿明'] }, { alphabet: 'B', name: ['白花', '百明', '白花', '百明', '白花', '百明', '白花', '百明', '白花', '百明'] }, // ......... 数据 ] } }, mounted() { }, methods: { getLetter(item) { this.letterTipFlag = true this.letterTipText = item clearTimeout(this.timer) this.timer = setTimeout(() => { let lastDom = this.lastLetterDom if(lastDom) { this.$refs[lastDom][0].classList.remove('active') } let letterDom = this.$refs['ref' + item][0] // console.log(letterDom) this.lastLetterDom = 'ref' + item letterDom.classList.add('active') setTimeout(() => { letterDom.classList.remove('active') this.letterTipFlag = false }, 300) let id = '#' + item const alphaDom = document.querySelector(id) if(alphaDom) { alphaDom.scrollIntoView(true) } }, 10) }, touchMove(event) { let x = event.changedTouches[0].clientX let y = event.changedTouches[0].clientY let xx = document.elementFromPoint(x,y) if(xx.tagName.toLowerCase() === 'p') { let item = xx.innerHTML this.getLetter(item) } } } }
其他:为了减少篇幅,省略样式