<div class="textarea-prepend"><textarea rows="6" placeholder="请输入消息内容"></textarea></div> .textarea-prepend {position: relative;}.textarea-prepend textarea {width: 300px;}.textarea-prepend::before {background-color: #f5f7fa;color: #909399;display: block;position: absolute;/* 重要,可获取元素上携带的 data-* 的属性 */content: attr(data-content);top: 1px;left: 1px;border-radius: 4px;padding: 4px;white-space: nowrap;line-height: normal;font-size: 12px;} const el = document.querySelector('.textarea-prepend');// 设置签名数据const smsSign = '我的签名abc';// 收集数字、字母 [] 长度let charLength = 0;for (let i = 0; i < smsSign.length; i++) {if (/[a-z0-9]/i.test(smsSign[i]) || ['[', ']'].includes(smsSign[i])) {charLength++;}}// 数字、字母、【】占用1个位置,汉字占用2个位置,用于正确设置 textIndent 偏移量const smsSignTotalLength = smsSign.length - charLength + charLength / 2;el.setAttribute('data-content', smsSign);// 设置input偏移量, 相对于父元素el.querySelector('textarea').style.textIndent = `${smsSignTotalLength + 0.5}em`;