实现文本框插入标签的参考方案

文本框插入标签

近期产品需求遇到一个类似某音插入话题标签的功能,思考了如何实现后做成考题给应聘前端的面试者,发现还是很多人没有思路的,所以实现以后分享一下自己的思路

  1. 使用富文本的方式,需引入第三方富文本组件且需去除无关功能,最后正则匹配替换高亮代码块提交后端接口

  2. DIV使用以下代码,并用js操作dom和数据进行逻辑交互,最后正则匹配替换高亮代码块提交后端接口

    -webkit-user-modify: read-write-plaintext-only !important;
    

    ps:这个属性有四个可选值:

    read-only:默认值,元素只读,不可编辑;

    read-write:可以编辑,支持富文本;

    read-write-plaintext-only:可以编辑,不支持富文本;

    write-only:使元素仅用于编辑(几乎没有浏览器支持);

  3. 使用障眼法,在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博客

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

xiaokar的日常cv

您的打赏是我持续创作的动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值