在后台管理系统中用户输入内容需要对特殊字符进行颜色标识,这里使用到的是elementPlus,因为输入框是字符串无法做颜色标识,只能使用标签形式来做颜色标识。使用定位将渲染元素和输入框重合在一起,输入框背景透明、颜色透明,循环输入元素对每个元素进行判断,是否需要颜色标记,有的话插入一个带class标签span来处理
<template><divclass="keywordInputContainer"><!--和输入层完全重叠,负责渲染标色文字--><divclass="highlightDev"v-html="highlightedText"></div><!--透明,仅负责编辑--><el-inputclass="highlightInput"v-model="inputData"type="textarea"resize="none"@input="handleInput"/></div></template><script lang="ts"setup>constinputData=ref('')consthighlightedText=ref('')consthighlightBracketContent=(inputText:string)=>{if(!inputText)return''letresult=''constinputTextNew=JSON.parse(JSON.stringify(inputText))// 遍历每个字符处理for(leti=0;i<inputTextNew.length;i++){constchar=inputTextNew[i]// 获取字符ASCII编码(十进制)constasciiCode=char.charCodeAt(0)letcharHtml=''// 1. 控制字符(0-31、127)if((asciiCode>=0&&asciiCode<=31)||asciiCode===127){charHtml=`<span class="highlight-text">${char}</span>`}// 2. 显示字符(32-126)elseif(asciiCode>=32&&asciiCode<=126){charHtml=`<span class="highlight-text">${char}</span>`}else{charHtml=char}result+=charHtml;}returnresult;}// 实时输入触发标色consthandleInput=()=>{highlightedText.value=highlightBracketContent(inputData.value);}watch(inputData,handleInput,{immediate:true});</script><style scoped lang="scss">:deep(.highlight-text){background:#fbde28!important;margin:0!important;padding:0!important;border:none!important;// background: none !important;font-weight:inherit!important;font-size:inherit!important;line-height:inherit!important;font-family:inherit!important;vertical-align:baseline!important;}.keywordInputContainer{width:100%;height:100%;position:relative;.highlightDev{position:absolute;top:0;left:0;height:100%;width:100%;padding:8px11px!important;box-sizing:border-box;font-family:"Helvetica Neue",Helvetica,"PingFang SC","Hiragino Sans GB","Microsoft YaHei",sans-serif!important;font-size:14px!important;line-height:1.5!important;word-break:break-all;white-space:pre-wrap;overflow-y:auto;pointer-events:none;z-index:1;}// 输入层:透明,仅保留编辑功能:deep(.highlightInput){position:relative;width:100%;height:100%;box-sizing:border-box;z-index:999;.el-textarea__inner{background-color:transparent!important;color:transparent!important;-webkit-text-fill-color:transparent!important;caret-color:#333!important;padding:8px11px!important;font-family:"Helvetica Neue",Helvetica,"PingFang SC","Hiragino Sans GB","Microsoft YaHei",sans-serif!important;font-size:14px!important;line-height:1.5!important;word-break:break-all;white-space:pre-wrap;border:1px solid #dcdfe6!important;resize:none!important;&:focus{caret-color:#409eff!important;border-color:#409eff!important;}}}}</style>