通过单词编号选择Rangy库的范围

时间:2018-08-27 17:22:56

标签: html range highlight rangy

我正在测试Rangy库以突出显示文本。选择和突出显示文本似乎很容易。但是,我面临以下情况:

说有一个文本(HTLM页面)和给定的单词位置范围(例如10到23)。有没有办法用兰吉语中的数字来创建此范围的单词,以使其突出显示?

谢谢。

更新

以下是HTML内容的示例:

<div id = "content">
   <h3>World human population</h3>
   <div class="aright w300 shadow">
     <a href="img308.jpg" " title='Population growth.'" >
       <img id_image="308" src="img308.jpg" /></a>
       <div class="iphoto">Population growth.</div>
   </div>
   <p>The world's population is estimated to be 7.646 billion.</p>

   <h3>The development of agriculture and manufacturing</h3>

   <ul class="bullets color">
     <li>
       <p> <strong>Predicted growth.</strong> Population growth increased significantly as the Industrial Revolution gathered pace from 1700 onwards.</p>
     </li>
     <li>
       <p> <strong>Predicted decline.</strong> In the future, the world's population is expected to peak,[17] after which it will decline due to economic reasons, health concerns, land exhaustion and environmental hazards.</p>
     </li>
   </ul>
</div>

如何在“估计”(第10个词)和“增长”(第24个词)之间创建所选词的范围?

1 个答案:

答案 0 :(得分:0)

您将要使用带正则表达式的findText方法来匹配正确的单词。不带正则表达式的Rangy代码的伪代码:

var searchResultApplier = rangy.createClassApplier("classToApply");
var range = rangy.createRange();
var searchScopeRange = rangy.createRange();
searchScopeRange.selectNodeContents(document.querySelector('#content');
searchResultApplier.undoToRange(range);

searchTerm = new RegExp('your regex to select the correct range of words');
if (range.findText(searchTerm, options) {
    searchResultApplier.applyToRange(range);  // Apply your class
}

这取自Rangy库随附的演示代码,这是一个很好的测试工具。