我正在制作一个程序来搜索所需 <textarea>
中的字符.我需要为在文本区域中找到的特定字符着色。如何为 <textarea>
中的字符着色?例如,如果我在输入字段中输入“a”而不是 <textarea>
中的所有“a”应该染成红色......
HTML
<form method="post" name="searching" onSubmit="return check(this)">
<table border="0" cellpadding="10px" align="center">
<tr><td width="114">
<label><b>Text</b></label></td>
<td width="287">
<textarea name="para" cols="30" rows="10"></textarea>
</td>
</tr>
<tr>
<td>
<label><b>Alphabet</b></label>
</td>
<td><input type="text" name="character" title="Enter Character">
</tr>
<tr>
<td colspan="2" align="center">
<input id="btn" type="submit" name="submit" value="Search">
</td>
</tr>
</table>
</form>
JS
<script language="javascript">
function check(form)
{
if(form.para.value==""){
alert("No text is available for search!!");
return false;
}
if(form.character.value=="")
{
alert("Search keyword is not Enter!!");
return false;
}
para=new Array();
index=new Array();
keyword=form.character.value;
para=form.para.value;
found=0;
k=0;
for(i=0; i<para.length;i++)
{
if(keyword==para[i]){
found+=1;
$(document).ready(function(e) {
$("textarea:eq(i)").css("color","#FF0000");
});
index[k++]=i;
}
}
if(found!=0){
alert(found+" times "+keyword+" in text");
alert("Index of alphabet: "+index);
return false;
}
else{
alert("Not found in the Text!!");
return false;
}
}
</script>
我正在寻找任何解决方案,无论是 CSS、HTML、JS(还是 jQuery)。谢谢。
最佳答案
正如@Mohamed-Yousef 在他的评论中所说,我认为您不能将标签或样式放在 <textarea>
中。 .
另一种方法是使用用户可编辑的 <div>
.这样,您就可以通过 JS 放置带有样式的附加标签。
例如:
<div contenteditable="true">
<!-- Editable like a textarea, but without some of its default styles and functions -->
This is the text in which to highlight letters.
</div>
有了这个,如果你搜索“e”,你可以制作一个 JS 脚本来在所有“e”周围添加样式元素,这样你的 <div>
(文本区域)看起来像这样:
<div contenteditable="true">
This is the t<span style="background-color: yellow">e</span>xt in which to highlight l<span style="background-color: yellow">e</span>tt<span style="background-color: yellow">e</span>rs.
</div>
尝试 this example (结果真的很好,我很惊讶)。
关于javascript - 如何为文本区域中的特定字符着色,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33464217/