I want to achieve a python version web regexbuddy,and i encounter a problem,how to highlight mat开发者_如何学Pythonch values in different color(switch between yellow and blue) in a textarea,there has a demo what exactly i want on http://regexpal.com,but i was a newbie on js,i didn't understand his code meaning. any advice is appreciated
To save time you should consider using an existing library for this requirement.
Quote from here:
As textarea elements can’t render HTML, this plugin allows you to highlight text inside textarea elements.
jQuery highlightTextarea.
Demo: Codepen
Usage:
$context.highlightTextarea(options);
There is a pre
element over the textarea. So when you type anything it is copying the input on the pre
element, applying some filters.
For example:
<pre id="view"></pre>
<textarea id="code"></textarea>
When you type on #code
it is copying the value, applying filters and adding the HTML to the #view
.
var code = document.getElementById("code");
var pre = document.getElementById("pre");
(code).onkeyup = function (){
val = this.value;
val = YourRegex(val);
(pre).innerHTML = val;
};
YourRegex
would be a method to match the regex
and return some parsed content to the pre
, allowing you to customize the appearance of the textarea
(that is actually an element over it).
function YourRegex(val)
{
// This function add colors, bold, whatever you want.
if (/bbcc/i.test("bbcc"))
return "<b>" + val + "</b>";
}
@BrunoLM's solution is excellent, but might require more hacking than you're comfortable with. If you're interested (and if jQuery is already in your stack), the following plugin may be worth taking a look at:
http://garysieling.github.io/jquery-highlighttextarea/
精彩评论