安装emoji-mart-vue插件
插件地址: https://github.com/jm-david/emoji-mart-vue
需要注意的细节:
- 获取光标位置
- 插入完成后的光标位置,vue的v-model渲染会有一个过程,需要加一个延时再去计算移动光标位置
示例图:
完整代码
<template>
<div>
<textarea id="textarea" v-model="content" />
<div class="face">
<Picker @select="showEmoji" :i18n="I18N" />
</div>
</div>
</template>
<script>
import { Picker } from "emoji-mart-vue";
const I18N = {
search: '搜索',
notfound: 'No Emoji Found',
categories: {
search: '搜索结果',
recent: '经常使用',
smileys: '表情与情感',
people: '人物与身体',
nature: '动物与自然',
foods: '食物与饮料',
activity: '活动',
places: '旅行与地理',
objects: '物品',
symbols: '符号标志',
flags: '旗帜',
custom: 'Custom',
},
}
export default {
name: 'App',
components: {
Picker
},
data() {
return {
content: '',
I18N: I18N
}
},
methods: {
// 选择表情
showEmoji(emoji) {
const str = emoji.native
var oText = document.getElementById('textarea')
var index = this.getCursortPosition(oText)
this.$nextTick( () => {
this.insert(oText,str,index)
})
},
// 插入表情
insert (oText,varstr,index) {
var text = this.content
let startStr = text.substring(0, index)
let endStr = text.substring(index, text.length)
this.content = startStr + varstr + endStr
setTimeout(() => {
this.setCaretPosition(oText, index+2)
}, 10);
},
// 获取光标位置
getCursortPosition (obj) {
var cursorIndex = 0
if (document.selection) {
obj.focus()
var range = document.selection.createRange()
range.moveStart('character', -obj.value.length)
cursorIndex = range.text.length
} else if (obj.selectionStart || obj.selectionStart == 0) {
cursorIndex = obj.selectionStart
}
return cursorIndex
},
// 设置光标位置
setCaretPosition(ctrl, pos){
if(ctrl.setSelectionRange)
{
ctrl.focus();
ctrl.setSelectionRange(pos,pos);
}
else if (ctrl.createTextRange) {
var range = ctrl.createTextRange();
range.collapse(true);
range.moveEnd('character', pos);
range.moveStart('character', pos);
range.select();
}
},
}
}
</script>
<style>
textarea{
width: 100%;
height: 200px;
padding: 10px;
line-height: 24px;
}
</style>