在我们使用聊天工具进行聊天的时候经常会用到表情符号, 有时我们会需要将文字与表情混输, 本文就来为大家介绍一下使用 vue 实现文字表情混输的方法.
实现思路
利用 div 的 contenteditable 属性, 让 div 可编辑
绑定 ref 属性, 用于操作输入框元素
图片点击时, 获取图片地址, 使用 require 转换图片地址
创建 img 标签, 赋值转换好的图片地址
从 refs 对象中获取到输入框元素, 赋值创建好的 img 标签
实现过程
声明 div 可编辑, 监听回车键事件, 关闭拼写检查, 绑定 ref 方便获取当前元素
- <div class="input-panel" ref="msgInputContainer" @keydown.enter.exact="sendMessage($event)"
- contenteditable="true" spellcheck="false"></div>
表情输入框绑定对应的事件
- <div class="item-panel" v-for="item in this.emojiList" :key="item.info">
- <img :src="require(`../assets/img/emoji/${item.src}`)" :alt="item.info"
- @mouseover="emojiConversion($event,'over',item.src,item.hover,item.info)"
- @mouseleave="emojiConversion($event,'leave',item.src,item.hover,item.info)"
- @click="emojiConversion($event,'click',item.src,item.hover,item.info)">
- </div>
实现表情框图片点击事件
- emojiConversion: function (event, status, path, hoverPath, info) {
- if (status === "over") {
- event.target.src = require(`../assets/img/emoji/${hoverPath}`);
- } else if (status === "click") {
- // 表情输入
- const imgSrc = require(`../assets/img/emoji/${hoverPath}`);
- /**
- * 不推荐的写法:
- * 无法获取焦点
- * 无法在当前焦点的位置插入元素
- */
- // const imgTag = document.createElement("img");
- // imgTag.src = imgSrc;
- // imgTag.alt = info;
- // this.$refs.msgInputContainer.appendChild(imgTag);
- /**
- * 推荐使用 document 暴露的 execCommand 方法来操作此处
- * 可以在当前焦点处插入元素
- * 感谢评论区掘友的建议
- */
- const imgTag = `<img src="${imgSrc}" width="28" height="28" alt="${info}">`;
- document.execCommand("inserthtml", false, imgTag);
- } else {
- event.target.src = require(`../assets/img/emoji/${path}`);
- }
- }
踩坑记录
直接使用 append() 方法
一直用 jQuery, 类似的需求直接 append, 以为是 JS 提供的方法, 结果这里直接使用, 答案很明显, 直接将 DOM 字符串插入了输入框里
手动实现字符串转 dom
正确的实现方法
创建 DOM 字符串, 使用 document 暴露的 execCommand 方法来插入创建好的 DOM 字符串.
不过 execCommand 的兼容性欠佳, 如果遇到没反应的情况, 是你的浏览器不支持此 API.
如果考虑兼容性问题可使用文中提到的另一种写法
- // const imgTag = document.createElement("img");
- // imgTag.src = imgSrc;
- // imgTag.alt = info;
- // this.$refs.msgInputContainer.appendChild(imgTag);
项目地址: https://github.com/likaia/chat-system
更多前端开发学习 https://www.html.cn/ 知识, 请关注 HTML 中文网
来源: http://www.css88.com/web/vue-js/18983.html