首页 > 解决方案 > 使用 Rangy 库按字号选择范围

问题描述

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

假设有一个文本(HTLM 页面)和给定的单词位置范围(例如,10 到 23)。有没有办法在 Rangy 中用数字创建这个范围的单词,以突出显示它?

谢谢你。

更新

以下是 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 个单词)之间创建选定单词的范围?

标签: htmlrangehighlightrangy

解决方案


您将需要使用带有正则表达式的 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 库提供的演示代码中获取的,这是一个很好的测试工具。


推荐阅读