如何制作像Twitter一样的字符限制突出显示的textarea? [英] How can I make a textarea with character limit highlighting like Twitter?
问题描述
Twitter的提交推文文本框突出显示超出角色限制的字符:
Twitter's submit tweet textbox highlights the characters that are over the character limit:
如您所见,超出字符限制的字符以红色突出显示。我怎样才能实现这样的目标?
As you can see, the characters that overrun the character limit are highlighted in red. How can I achieve something like this?
推荐答案
您可以在这里找到必要的解决方案和所需代码:
You'll find the necessary solution and required code here:
...这里:
< a href =https://stackoverflow.com/questions/20314126/regex-highlight-part-over-19-chars> REGEX - 突出超过19个字符的部分
您的问题似乎是双重的。
Your question appears to be duplicitous.
注意:我没有选择将上述链接作为评论发布(即特权取决于声誉)。
Note: I didn't have the option to post the above links as a comment (i.e. privilege contingent on reputation).
以下是根据Simon Kuang的推荐代码(见评论):
Here's the code as per Simon Kuang's recommendation (see comments):
<!DOCTYPE html>
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js"></script>
<meta charset=utf-8 />
<title>JS Bin</title>
</head>
<body>
<h3>Your text here</h3>
<div contenteditable="true" id="myDiv">edit me
</div>
<p>
<h3>Stuff over 19 characters</h3>
<div id="extra">
</div>
<p>
<h3>Sample output</h3>
<div id="sample">
</div>
</body>
</html>
CSS:
CSS:
.highlight {
color:red;
}
JavaScript:
JavaScript:
$(document).ready(function() {
$('#myDiv').keyup(function() {
var content = $('#myDiv').html();
var extra = content.match(/.{19}(.*)/)[1];
$('#extra').html(extra);
var newContent = content.replace(extra, "<span class='highlight'>" + extra + "</span>");
$('#sample').html(newContent);
});
});
这篇关于如何制作像Twitter一样的字符限制突出显示的textarea?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!