使用另一个div的内容突出显示文本内容

时间:2018-11-12 18:11:41

标签: javascript html css

我想使用另一个div中的文本内容突出显示段落中的文本内容。因此,在第一个div中有“增加总体代码”。我希望通过第一格突出显示主要段落中的这些词。感谢您有可能在这里寻求帮助!

function highlight() {
  var htext = document.getElementById("torles");
  var inputText = document.getElementById("inputText");
  var innerHTML = inputText.innerHTML;
  var index = innerHTML.indexOf(text);
  if (index >= 0) {
    innerHTML = innerHTML.substring(0, index) + "<span class='highlight'>" + innerHTML.substring(index, index + text.length) + "</span>" + innerHTML.substring(index + text.length);
    innerHTML.innerHTML = innerHTML;
  }
}
.highlight {
  background-color: red;
}
<html>

<body>
  <div class="col-md-10 bordered selectborder fragment" id="torles">increase overall coder
  </div>
  <button onclick="highlight()">Highlight</button>

  <div class="col-md-10 para bordered" id="inputText">
    <strong><p>Significantly Reduce Costs and Improve Quality with an Experienced, Professional Global Coding Solution. Health Information Management (HIM) Directors and CFOs are seeking innovative ways to reduce expenses, maintain DNFB goals, and increase overall coder quality.</p></strong>
  </div>
</body>

</html>

1 个答案:

答案 0 :(得分:1)

因此,有几件事;但首先,这是一个有效的示例。

function highlight() {
  var text = document.getElementById("torles").textContent;//you want the text not the node
  var inputText = document.getElementById("inputText");
  var innerHTML = inputText.innerHTML;
  var index = innerHTML.indexOf(text);
  if (index >= 0) {
    innerHTML = innerHTML.substring(0, index) + "<span class='highlight'>" + innerHTML.substring(index, index + text.length) + "</span>" + innerHTML.substring(index + text.length);
    inputText.innerHTML = innerHTML;//this line was incorrect
  }
}
.highlight {
  background-color: red;
}
<html>

<body>
  <div class="col-md-10 bordered selectborder fragment" id="torles">increase overall coder</div><!-- make sure there's no line break after "coder"-->
  <button onclick="highlight()">Highlight</button>

  <div class="col-md-10 para bordered" id="inputText">
    <strong><p>Significantly Reduce Costs and Improve Quality with an Experienced, Professional Global Coding Solution. Health Information Management (HIM) Directors and CFOs are seeking innovative ways to reduce expenses, maintain DNFB goals, and increase overall coder quality.</p></strong>
  </div>
</body>

</html>

无论如何,主要有三件事(和错别字)。首先,您在increase overall coder之后的HTML中有一个换行符,因此它将尝试在文本中找到带有换行符的字符串,因此就找不到了。 / p>

第二,您混淆了变量的实际含义;首先,text变量(您将其拼写为htext)是一个节点,而不是字符串。另外,您尝试设置innerHTML中的innerHTML,但是变量innerHTML只是一个字符串。您想要设置节点的innerHTML(在这种情况下为inputText)。