簡體   English   中英

使用jQuery在文本區域內匹配並突出顯示標簽/單詞(更改顏色和字體粗細)

[英]Matching and highlighting tags/words (changing color and font-weight) inside textarea using jQuery

我在textarea ,當我添加在數組中定義的tags時,我才開始輸入,因此根據我的條件,它應該in arrayin arraynot 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> 

我只是開始輸入此文This is not what we want {email} {rec1_full_name}盡管我的電子郵件標簽是在textarea中鍵入的,但它顯示的消息not in array所以如何在鍵入過程中以及在匹配標簽后匹配標簽將其顏色更改為藍色,將其字體更改為粗體。

1)您的代碼無效,因為您一次讀取了textarea的值,並且在鍵入時此變量沒有更改;

2)使用$.inArray(txtArea, tagsArray)嘗試檢查數組中是否包含不正確的完整字符串。 為此使用RegExp會更好:

 $(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"); } }); }); 
 <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> 

3)您不能將樣式應用於帶有文本區域的單獨單詞。 看到這個問題 可能您需要采用其他方法,例如類似這樣的方法 -這里的想法是將div元素作為背景,並在此元素和textarea之間同步內容。

更新: 4)您可以嘗試在div元素上使用contenteditable="true" ,這將使內部內容可編輯,因此您的div行為類似於富文本編輯器。 這是一個有關如何實現此目標的快速示例。 希望這個想法對您有幫助(我不會為您編寫全部功能,只想舉例說明概念以及您對問題有哪些選擇)。

 $(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 }; } }); 
 div#txtarea { width: 150px; height: 150px; border: 1px solid black; overflow: auto; } mark { color: blue; font-weight: bold; background: transparent } 
 <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> 

我為您提供解決方案。 希望這會有所幫助。

<!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>

 $(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> 

使用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> 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM