使用 highlighttextarea 插件突出显示 textarea 中的文本(如果不在数组中)
Highlight Text in textarea if not in the array using highlighttextarea plugin
我正在使用 jQuery highlightTextarea 插件来突出显示 html textarea 中的单词。
它目前突出显示数组中的那些词,
var words = ['google', 'facebook', 'github', 'microsoft', 'yahoo', 'Whosebug'];
但我想做的是突出显示所有不在数组中的单词。有什么办法可以做到这一点吗?
我的 jsfiddle:http://jsfiddle.net/fr7wb2b4/11/
笨蛋我还没想好,这个呢:
$(document).ready(function () {
var words = ['google', 'facebook', 'github', 'microsoft', 'yahoo', 'Whosebug'];
$('#textarea').highlightTextarea({
words: [
{ color : '#F00',
words : ['(.+)']
}, // Make everything highlighted
{ color : '#FFF',
words : words
} // Make white what matched
]
});
});
您也可以使用 words : ['(\w+)']
仅突出显示最初的单词
你可以看看库源码,高亮代码:https://github.com/mistic100/jquery-highlighttextarea/blob/master/jquery.highlighttextarea.js#L67
实际突出显示的片段是:
$.each(this.settings.words, function(color, words) {
text = text.replace(
new RegExp(that.spacer+'('+ words.join('|') +')'+that.spacer, that.regParam),
'<mark style="background-color:'+ color +';"></mark>'
);
});
所以您可以用您自己的函数替换 highlight
函数,并执行您选择的任何逻辑来突出显示(开源万岁!)
例如,您可以复制粘贴整个函数,只需将 $.each(words...
循环替换为以下内容即可:
var replaced = '',
tokens = text.split(' ');
$.each(tokens, function(ind, token) {
if (this.settings.words.indexOf(token) != -1) {
// this token in the text is part of the 'words' - do not highlight
replaced += token;
}
else {
// this token isn't part of the words - highlight it
replaced += '<span style="...">'+token+'</span>';
}
replaced += ' ';
}
text = replaced;
我正在使用 jQuery highlightTextarea 插件来突出显示 html textarea 中的单词。
它目前突出显示数组中的那些词,
var words = ['google', 'facebook', 'github', 'microsoft', 'yahoo', 'Whosebug'];
但我想做的是突出显示所有不在数组中的单词。有什么办法可以做到这一点吗?
我的 jsfiddle:http://jsfiddle.net/fr7wb2b4/11/
笨蛋我还没想好,这个呢:
$(document).ready(function () {
var words = ['google', 'facebook', 'github', 'microsoft', 'yahoo', 'Whosebug'];
$('#textarea').highlightTextarea({
words: [
{ color : '#F00',
words : ['(.+)']
}, // Make everything highlighted
{ color : '#FFF',
words : words
} // Make white what matched
]
});
});
您也可以使用 words : ['(\w+)']
仅突出显示最初的单词
你可以看看库源码,高亮代码:https://github.com/mistic100/jquery-highlighttextarea/blob/master/jquery.highlighttextarea.js#L67
实际突出显示的片段是:
$.each(this.settings.words, function(color, words) {
text = text.replace(
new RegExp(that.spacer+'('+ words.join('|') +')'+that.spacer, that.regParam),
'<mark style="background-color:'+ color +';"></mark>'
);
});
所以您可以用您自己的函数替换 highlight
函数,并执行您选择的任何逻辑来突出显示(开源万岁!)
例如,您可以复制粘贴整个函数,只需将 $.each(words...
循环替换为以下内容即可:
var replaced = '',
tokens = text.split(' ');
$.each(tokens, function(ind, token) {
if (this.settings.words.indexOf(token) != -1) {
// this token in the text is part of the 'words' - do not highlight
replaced += token;
}
else {
// this token isn't part of the words - highlight it
replaced += '<span style="...">'+token+'</span>';
}
replaced += ' ';
}
text = replaced;