实现这么一个需求:
chat聊天组件,需要有emoji表情包, 并实现点击赋值在文本输入框中。
实现原理:
有一个emoji表情png图,并对应json对照表,文字对应样式类型。并有一个对应的样式文件。这个在我的另外一篇文章:emoji.js 。这篇文章有对应的json文件和写好的样式,直接拿来用即可。
剩下就是根据json对照表循环将对应的表情渲染出来,并添加点击事件。
直接开撸代码
<template lang="pug">
ul.emoji-box(v-if='emojiObj && Object.keys(emojiObj).length')
li.emoji-li(v-for="item in Object.keys(emojiObj)" :key="item" @click="insetEmoji")
span.small.qqface(:class="emojiObj[item]") {{item}}
</template>
<script>
import emojiJson from '@/utils/emoji'
export default {
name: 'EmojiBox',
data(){
return{
emojiObj: emojiJson
}
},
methods: {
insetEmoji(e){
let val = e.target.innerText
let elInput = document.getElementById('im-input')
let startPos = elInput.selectionStart
let endPos = elInput.selectionEnd
if (startPos === undefined || endPos === undefined) return
let txt = elInput.value
let result = txt.substring(0, startPos) + val + txt.substring(endPos)
elInput.value = result
this.$emit('changeVal', result)
elInput.focus()
elInput.selectionStart = startPos + val.length
elInput.selectionEnd = startPos + val.length
this.$emit('closeEmoji')
}
}
}
</script>
<style lang="scss" scoped>
@import "@/assets/css/emoji.scss";
.emoji-box{
width: 100%;
height: 400px;
overflow: hidden;
display: flex;
flex-wrap: wrap;
justify-content: flex-start;
&:hover{
overflow-y: scroll;
}
.emoji-li{
width: 40px;
height: 40px;
text-align: center;
.qqface{
vertical-align: super;
&:hover{
transform: scale(1.5);
cursor: pointer;
}
}
}
}
</style>