知识在于积累,踩坑越多,你越强😎
用多了JQuery,习惯了使用JQuery的API操作DOM,几乎忘记了原生JS对DOM操作,今天在项目中遇到了文字和图片混输的情况,第一个想到的办法是用textarea实现,结果发现实现不了图片输入,然后想着找个富文本编辑器的插件实现,深思熟虑之后,我的需求好像也没那么复杂,不至于引用个插件,看了掘金的发布沸点功能,然后就模仿了其作法,于是就有了这篇文章的分享。先给大家展示下最后实现的效果😋
•利用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。(图片源自mdn)
•如果考虑兼容性问题可使用文中提到的另一种写法
// const imgTag = document.createElement("img");
// imgTag.src = imgSrc;
// imgTag.alt = info;
// this.$refs.msgInputContainer.appendChild(imgTag);
•文中如有错误,欢迎在评论区指正