文本框插入标签
近期产品需求遇到一个类似某音插入话题标签的功能,思考了如何实现后做成考题给应聘前端的面试者,发现还是很多人没有思路的,所以实现以后分享一下自己的思路
-
使用富文本的方式,需引入第三方富文本组件且需去除无关功能,最后正则匹配替换高亮代码块提交后端接口
-
DIV使用以下代码,并用js操作dom和数据进行逻辑交互,最后正则匹配替换高亮代码块提交后端接口
-webkit-user-modify: read-write-plaintext-only !important;
ps:这个属性有四个可选值:
read-only:默认值,元素只读,不可编辑;
read-write:可以编辑,支持富文本;
read-write-plaintext-only:可以编辑,不支持富文本;
write-only:使元素仅用于编辑(几乎没有浏览器支持);
-
使用障眼法,在textarea上面定位一个div并使用v-html富文本渲染,使用pointer-events: none;进行穿透可输入处理,使用watch区分字段做富文本高亮替换处理,最后提交正常输入的值给后端接口即可
//template片段 <div class="addBox"> <p class="add" @click="addLink">插入联系方式</p> <a-input class="editInput" v-model="form.content" :maxLength="100" placeholder="请输入" type="textarea" > </a-input> <!-- 高亮遮罩处理 --> <div class="editDiv" v-html="contentHtml"></div> <span>{{ form.content.length || 0 }}/100</span> </div> //script片段 computed: { formContent(){ return this.form.content } }, watch:{ formContent:{ handler(newVal,oldVal){ this.contentHtml = newVal.replace(/#联系方式#/g,`<span style="color:#40a9ff;">#联系方式#</span>`) }, immediate:true, deep:true, } }, //less片段 .addBox { position: relative; span { position: absolute; left: calc(80% - 42px); bottom: -30px; } .add { margin-bottom: 0; color: rgb(64, 169, 255); cursor: pointer; } .editDiv, .editInput { width: 80%; height: 200px !important; max-width: 100%; line-height: 1.5; vertical-align: bottom; margin-right: 8px; border: 1px solid #d9d9d9; border-radius: 4px; position: relative; z-index: 1; padding: 4px 11px; &:hover, &:focus, &:focus-visible { border: 1px solid #40a9ff !important; } } .editDiv { position: absolute; bottom: 4px; pointer-events: none; z-index: 2; background: transparent; } }
原文博客地址:xiaokar博客