文本区域标签高亮显示应用于第一行之后的错误位置

Textarea hashtag highlight is applied to the wrong position after the first line

本文关键字:一行 之后 位置 错误 标签 区域 高亮 显示 应用于 文本      更新时间:2023-09-26

当我要转到新行并从该行的开头开始标签时,荧光笔会将颜色应用到前一行。

  <style>
        #input{
            color: transparent;
        }
        #input b{
            text-decoration: none;
            color: transparent;
            background-color: #9aceff;
            font-weight: normal;
        }
        #t{
          background-color: transparent;            
        }
    </style>
<textarea id="t" style="width: 342px; height: 92px; resize: none; position: absolute; z-index: 1; border: 1px solid #212;font-family: arial; padding: 20px; margin: 0; font-size: 12px;">
</textarea>
<div style="width: 300px; height: 50px; border: 1px solid #212; font-family: arial; padding: 20px; position: absolute; z-index: 0; margin: 0; font-size: 12px;" id="input">
</div>
<script>
$(document).ready(function(){
   $('#t').on('input keyup', function() {
       var str = $(this).val();       
       str = str.replace(/(<.+?>)/gi, '');        
       str = str.replace(/(?:'s|^)#([^0-9'W's][a-zA-z0-9]*)/g, ' <b>#$1</b>');       
       str = str.replace(/(?:'r'n|'n'r|'r|'n)/g, '<br />');       
       $('#input').html(str);
   });
});
</script>

这是我的jsfiddle代码。

您在这里面临的问题是,在<br />元素最终替换换行符之前,正则表达式正在用空格替换换行符。

因此,如果哈希字符串前面有换行符,高亮显示将出现在前一行,而不是正确地与哈希字符串放在同一行。

对此的一个快速解决方案是交换最后两个字符串替换,并在<br />后面添加一个空格,以避免它包含在散列字符串中:

$(document).ready(function(){
   $('#t').on('input keyup', function() {
       var str = $(this).val();       
       str = str.replace(/(<.+?>)/gi, '');
       str = str.replace(/(?:'r'n|'n'r|'r|'n)/g, '<br /> ');
       str = str.replace(/(?:'s|^)#([^0-9'W's][a-zA-z0-9]*)/g, ' <b>#$1</b>');       
       $('#input').html(str);
   });
});

下面是一个更新的JSFiddle演示。希望这能有所帮助!如果你有任何问题,请告诉我。