[英]Matching and highlighting tags/words (changing color and font-weight) inside textarea using jQuery
我在textarea
,当我添加在数组中定义的tags
时,我才开始输入,因此根据我的条件,它应该in array
说in array
但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>
我只是开始输入此文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.