首页 > 语言 > JavaScript > 正文

JS关键字变色实现思路及代码

2024-05-06 14:19:34
字体:
来源:转载
供稿:网友
1.替换关键字,对字体变色
代码如下:
public static string ReplaceRed(string strtitle, string redkey)
{
if (redkey == "" || redkey == null)
{
return strtitle;
}
else
strtitle = strtitle.Replace(redkey, " <font color='#ff0000'>" + redkey + " </font>");
return strtitle;
}

该方法缺点是:点字符是含大小写的英文时,变色后统一替换为了关键字的大小写,体验不好。
2.用正则,CSS背景变色
代码如下:
protected string HighlightText(string inputText,string searchWord)
{
System.Text.RegularExpressions.Regex expression = new System.Text.RegularExpressions.Regex(searchWord.Replace(" ", "|"), System.Text.RegularExpressions.RegexOptions.IgnoreCase);
return expression.Replace(inputText,new System.Text.RegularExpressions.MatchEvaluator(ReplaceKeywords));
}
public string ReplaceKeywords(System.Text.RegularExpressions.Match m)
{
return "<span class='highlightTxtSearch'>" + m.Value + "</span>";//关键字背景加色
//return "<font color='#ff0000'>" + m.Value + "</font>";//关键字变色
}

该方法可结合前台JS调用:
代码如下:
<style type="text/css">
.highlightTxtSearch
{
background-color:Yellow;
}
</style>

代码如下:
<script type="text/javascript">
$(function () {
$('#tt').datagrid({
url: '@Url.Content("~/Domain/LoadDomainAdmin")',
width: "90%",
height: 400,
fitColumns: true,
nowrap: false,
idField: 'UserID',
pagination: true,
pageNumber: 1,
singleSelect: true,
frozenColumns: [[{ field: 'radio', formatter: function (value, row, index) {
return '<input type="radio" name="rd_action" />';
}
}]],
columns: [[
{ field: 'UserID', title: 'UserID', width: 260, hidden: 'true' },
{ field: 'LoginName', title: '@ViewBag.LoginName', width: 180, align: 'left', formatter: function (data) {
//return "<div class='hiddenFontGommom' style='text-align:left;'>" + data + "</div>";
return GetNewData(data);
}
},
{ field: 'FirstName', title: '@ViewBag.FirstName', width: 120, align: 'left', formatter: function (data) {
//return "<div style='text-align:left;' title=" + data + ">" + data + "</div>";
return GetNewData(data);
// var keyword = $.trim($("#txtInfo").val()) == '@ViewBag.SearchText' ? "" : $.trim($("#txtInfo").val());
// if (keyword == "") {
// return "<div style='text-align:left;' title=" + data + ">" + data + "</div>";
// }
// else {
// var returnData = "";
// $.ajax({
// type: "POST",
// url: '@Url.Content("~/Domain/HighlightText")' + "?inputText=" + data + "&searchWord=" + keyword,
// async: false,
// success: function (newdata) {
// //重新赋值
// returnData = newdata;
// },
// error: function () {
// //不修改returnData值
// }
// });
// return "<div style='text-align:left;' title=" + data + ">" + returnData + "</div>";
发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表

图片精选