【问题标题】:Select range with Rangy library by word number使用 Rangy 库按字号选择范围
【发布时间】:2019-02-02 06:43:33
【问题描述】:

我正在测试 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 个单词)之间创建所选单词的范围?

【问题讨论】:

  • 您能否提供一些示例代码 sn-ps 以便我们更容易理解您的要求?
  • 我添加了一个 HTML 代码 sn-p 作为要突出显示的单词的示例。你是说这个?

标签: html range highlight rangy


【解决方案1】:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-13
    • 1970-01-01
    相关资源
    最近更新 更多