uniapp vue 长按选中单词高亮
<template>
<view>
<template v-for="(item, index) in processedText" :key="index">
<view v-if="!item.isSpace" :class="{'aaa':ids.indexOf(index) > -1}" class="word-view"
@longpress="onLongPress(item,index)">
{{ item.text }}
</view>
<text v-else>{{ item.text }}</text>
</template>
</view>
</template>
<script>
export default {
data() {
return {
text: 'The courage of life is often a less dramatic spectacle than the courage of a final moment; but it is no less magnificent mixture of triumph and tragedy. A man does what he must in spite of personal consequences, in spite of obstacles and dangers and pressures and that is the basis of all human morality.',
processedText: [],
ids: []
};
},
onLoad() {
this.processText();
},
methods: {
processText() {
const wordsAndSpaces = [];
let match;
const regex = /([a-zA-Z]+|[^\w\s]|\s+)/g;
while ((match = regex.exec(this.text)) !== null) {
const [fullMatch, word, punctuationOrSpace] = match;
if (word) {
wordsAndSpaces.push({
text: word,
isSpaceOrPunctuation: false,
isWord: true
});
} else {
wordsAndSpaces.push({
text: fullMatch,
isSpaceOrPunctuation: true,
isWord: false
});
}
}
this.processedText = wordsAndSpaces;
},
onLongPress(e, i) {
if (/^[^\w\s]+$/.test(e.text)) return
const index = this.ids.indexOf(i);
index > -1 ? this.ids.splice(index , 1) : this.ids.push(i);
}
}
};
</script>
<style>
.word-view {
display: inline-block;
margin-right: 4px;
color: pink;
}
.aaa {
color: #fff;
background-color: red;
}
</style>