【问题标题】:text highlighting using javascript使用javascript突出显示文本
【发布时间】:2012-06-14 00:10:26
【问题描述】:

我正在尝试使用 javascript 使用文本突出显示选项。我知道如何找到字符串的起始位置,但是如何使它突出显示。我的代码看起来像

<div id="entity">health insurance</div>
<div id="article">This kind of insurance is meant to supplement health insurance for cancer-care costs. But generally you're better off putting your money toward comprehensive health policies. </div>

还有我用过的javascript

$(document).ready(function()
{
var test=document.getElementById('article').innerHTML;
var variable=document.getElementById('entity').innerHTML;
alert(test.search(new RegExp(variable, "i")));
});

这将提醒字符串的起始位置。

【问题讨论】:

  • 澄清你的问题。你想强调什么,是包含文本的div吗?
  • 实体id里面的内容应该在文章id里面高亮..

标签: javascript jquery highlighting


【解决方案1】:

HTML:

<div id="entity">health insurance</div>
<div id="article">This kind of insurance is meant to supplement health insurance for cancer-care costs. But generally you're better off putting your money toward comprehensive health policies. </div>​

CSS:

.highlight {
  background-color: yellow
}

Javascript:

$(document).ready(function () {​
  var $test = $('#article');
  var entityText = $('#entity').html();
  var highlight = '<span class="highlight">' + entityText + '</span>';
  $test.html($test.html().replace(entityText, highlight));
}

演示:http://jsfiddle.net/ehzPQ/2/

所以,我只是将第一次出现的“实体”字符串替换为包含在跨度类中的相同字符串。

我是否正确理解了您的问题?

----------更新-------- -----

如果要突出显示所有出现的修改,请使用正则表达式:

更新的 Javascript:

$(document).ready(function () {
  var $test = $('#article');
  var entityText = $('#entity').html();
  var entityRegularExpression = new RegExp("\\b" + entityText + "\\b", "gi");
  var highlight = '<span class="highlight">' + entityText + '</span>';
  $test.html($test.html().replace(entityRegularExpression, highlight))
}

更新演示:http://jsfiddle.net/ehzPQ/3/

【讨论】:

  • 你能告诉我这个语句的作用吗' var entityRegularExpression = new RegExp(entityText,"g")' ?
  • 它使用'entityText'的内容创建一个正则表达式,'g'代表全局。因此,如果 'entityText = "foo"' 正则表达式将在字符串中查找所有出现的 'foo'。即它相当于'/foo/g'。
  • 如果 .或 $ 符号出现在匹配的 wrds 之间...使用这种形式,$ 或点符号不会被突出显示..
【解决方案2】:

只需将yourDesireString 替换为&lt;span class='highlight'&gt;yourDesireString&lt;/span&gt;

span.highlight {
     background-color: yellow;
}

【讨论】:

  • 它不会被修复...我刚刚给出了一个静态示例..如果我要突出显示的内容是实时生成的
  • 所以动态替换工作。
猜你喜欢
  • 2013-04-07
  • 1970-01-01
  • 1970-01-01
  • 2012-01-28
  • 2013-05-28
  • 2011-09-08
  • 2011-02-21
  • 2014-03-12
  • 2021-12-01
相关资源
最近更新 更多