使用jQuery匹配和突出显示textarea内的标签/单词(更改颜色和字体粗细)

时间:2017-06-21 10:40:35

标签: javascript jquery html

我已经textarea我刚刚开始输入我在数组中定义的tags,因此根据我的情况,它应该说in array,但它是在说{{} 1}}这是我的示例代码



not in array

$(document).ready(function() {
  var tagsArray = new Array("{full_name}", "{email}", "{company}", "{reg_no}", "{address}", "{city}", "{mobile}", "{rec1_full_name}", "{rec1_email}", "{rec2_full_name}", "{rec2_email}");
  var txtArea = $("textarea#txtarea").val();
  $(document).on("keyup", "#txtarea", function() {
    if ($.inArray(txtArea, tagsArray) != -1) {
      console.log("in array");
    } else {
      console.log("not in array");
    }
  });
});




我刚刚开始输入此文<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <textarea id="txtarea" name="txtarea" rows="10" cols="50"></textarea>,虽然我的电子邮件标签是在textarea中输入的,但它显示的是This is not what we want {email} {rec1_full_name}消息,所以如何在打字时匹配我的标签,匹配后我必须更改标签颜色为蓝色,字体为粗体。

4 个答案:

答案 0 :(得分:1)

1)您的代码无法正常工作,因为您只读了一次textarea的值,并且在您输入时此变量没有变化;

2)如果数组中包含的完整字符串不正确,则使用$.inArray(txtArea, tagsArray)。使用RegExp会更好:

&#13;
&#13;
$(document).ready(function() {
    var tagsArray = new Array("{full_name}", "{email}", "{company}");   
    $('textarea#txtarea').on('keyup', function() {
        var val = $(this).val();
        var searchExp = new RegExp(tagsArray.join("|"),"gi");
        if(searchExp.test(val)) {
            console.log("in array");
        } else {
            console.log("not in array");
        }
    });
});
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="container"> 
 <textarea id="txtarea" name="txtarea" rows="10" cols="50"></textarea>
</div>
&#13;
&#13;
&#13;

3)您无法使用textarea将样式应用于单独的单词。 See this question。您可能需要采用其他方法,例如like this - 这里的想法是将div元素作为背景并同步此元素与textarea之间的内容。

<强>更新 4)您可以尝试在div元素上使用contenteditable="true",这样内部内容就可以编辑,因此您的div可以像富文本编辑器一样运行。这是一个如何实现这一目标的简单示例。希望这个想法会对你有所帮助(我不打算为你编写完整的功能,只是想说明这个概念以及你对你的问题有什么选择)。

&#13;
&#13;
$(document).ready(function() {
    var tagsArray = new Array("{full_name}", "{email}", "{company}");   
    $('div#txtarea').on('keyup', function() {
        var $this = $(this); 
        //remember position of cursor before changing the content of the div element
        var restoreCursorPosition = saveCaretPosition(this);
        var val = $this.text(); 

        //highlight tags
        $this.html(val.replace(new RegExp(tagsArray.join("|"), "gi"), "<mark>$&</mark>"));
        //resore cursor position
        restoreCursorPosition();
    });
    
    function saveCaretPosition(context){
        var selection = window.getSelection();
        var range = selection.getRangeAt(0);
        range.setStart(context, 0 );
        var len = range.toString().length;

        return function restore(){
            var pos = getTextNodeAtPosition(context, len);
            selection.removeAllRanges();
            var range = new Range();
            range.setStart(pos.node ,pos.position);
            selection.addRange(range);

        }
    }

    function getTextNodeAtPosition(root, index){
        var lastNode = null;

        var treeWalker = document.createTreeWalker(root, NodeFilter.SHOW_TEXT,function next(elem) {
            if(index > elem.textContent.length){
                index -= elem.textContent.length;
                lastNode = elem;
                return NodeFilter.FILTER_REJECT
            }
            return NodeFilter.FILTER_ACCEPT;
        });
        var c = treeWalker.nextNode();
        return {
            node: c? c: root,
            position: c? index:  0
        };
    }
});
&#13;
div#txtarea {
  width: 150px;
  height: 150px;
  border: 1px solid black;
  overflow: auto;
}

mark {
  color: blue;
  font-weight: bold;
  background: transparent
}
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="container"> 
 <div id="txtarea" name="txtarea" contenteditable="true">
  Test input!
 </div>
</div>
&#13;
&#13;
&#13;

答案 1 :(得分:1)

我有一个解决方案。希望这会有所帮助。

<!DOCTYPE html>
<html>
<head>
  <title></title>
</head>
<body>

<textarea id="txtarea" name="txtarea" rows="10" cols="50"></textarea>
<button id="submitBtn">Submit</button>
<div id="displayContainer"></div>

<style type="text/css">
  .bold-blue{
    color: blue;
    font-weight: bold;
  }
</style>
<script src="https://code.jquery.com/jquery-3.2.1.js"
        integrity="sha256-DZAnKJ/6XZ9si04Hgrsxu/8s717jcIzLy3oi35EouyE="
        crossorigin="anonymous"></script>

<script type="text/javascript">
  function inArray(needle, haystack) {
    var length = haystack.length;
    for(var i = 0; i < length; i++) {
        if(haystack[i] == needle) return true;
    }
    return false;
}

$(document).ready(function() {
    var tagsArray = new Array("{full_name}", "{email}", "{company}", "{reg_no}", "{address}", "{city}", "{mobile}", "{rec1_full_name}", "{rec1_email}", "{rec2_full_name}", "{rec2_email}");

   $("#txtarea").on('keyup', function(e) {

      var tags = $("#txtarea").val().match("{(.*)}");

   //check whether the entered tag is valid
      for (tag in tags){
         if(!inArray(tags[tag], tagsArray)){
            if(tags[tag][0] == "{" && tags[tag][tags[tag].length-1] == "}"){
               //alert the user that he entered an invalid tag
               alert(tags[tag]+" is not a valid tag.");
            }
         }
      }
    });
   //render the tags blue and bold
     $("#submitBtn").on("click", function(){
      var tags = $("#txtarea").val().match("{(.*)}");
        var text = $("#txtarea").val();
        for (tag in tags){
          if(tags[tag][0] == "{" && tags[tag][tags[tag].length-1] == "}"){
           var newText = text.replace( tags[tag], '<span class="bold-blue">'+tags[tag]+'</span>');
          }
        }
        $("#displayContainer").html( newText );

     });

});
</script>
</body>
</html>

答案 2 :(得分:0)

$(document).on('keyup', function(e) {

var yourstring =$("P").html().match("{(.*)}")

   
for (i=0; i< yourstring.length; i++){

$('p:contains('+yourstring[i]+')', document.body).each(function(){
      
      $(this).html($(this).html().replace(
            new RegExp(yourstring[i], 'g'), '<span class=someclass>'+yourstring[i]+'</span>'
      ));
});
}
});
.someclass {
    color: blue;
    font-weight: bold;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
<p>
Lorem Ipsum is simply {email} {rec1_email} dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's 
printer took a galley of type and scrambled it to make a type specimen book. Lorem Ipsum has been the 
industry's standard dummy text ever since the 1500s, printe book.
</p>
<div>

答案 3 :(得分:0)

使用keyup,您可以随意应用样式,onfocus()

标签可编辑

  $(document).ready(function () {
        $('P').on("click", function () {
            $('P').attr("contenteditable", "true");
        });
    });

    $(document).on('keyup', function (e) {
        if (e.keyCode == 38) {
            var str = $('P').html();
            $('P').attr("contenteditable", false);
            var words = ["{full_name}", "{email}", "{company}", "{reg_no}", "{address}", "{city}", "{mobile}", "{rec1_email}"]

            var reg = RegExp(words.join('|'), 'gi')
            var p = document.createElement('p')
            p.innerText = str
            $('P').html($('P').html().replace(reg, '<b style="color:blue">$&</b>'));
        }
        else {
            $('P').attr("contenteditable", true);
        }
    });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>

    <p>
        Lorem Ipsum is simply {email} {rec1_email} dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's 
printer took a galley of type and scrambled it to make a type specimen book. Lorem Ipsum has been the 
industry's standard dummy text ever since the 1500s, printe book.
    </p>
<div>