代码之家  ›  专栏  ›  技术社区  ›  sagarkothari

通过特定坐标对单词应用DIV/Span标记

  •  1
  • sagarkothari  · 技术社区  · 16 年前

    示例HTML数据


    <body style="width:300px;">
    <h3>Long-Text</h3>
    A simple tool to store and display texts longer than a few lines.
    The search button will highlight all the words matching the name of objects that are members of the classes listed in searchedClasses, itself a member of the KeySet class. The highlighted words are hypertext.
    Edit invokes wscripts/acedb.editor, which by default launches emacs. Edit that file to start another editor in its place.
    Save will recover from the emacs but will not destroy it.
    Read will read a text file, so you could Search it.
    **general** grep is a way to annotate a set of longtexts versus the searchedClasses. It outputs an ace file that you can then hand check and read back in acedb to create XREF from longTexts to genes etc.
    <h3>World Wide NotePad</h3>
    World wide notepad is a small text editor similar to Microsoft's notepad but has some more useful features like an auto typer to make typing the same sentence or word more easy, also World Wide NotePad has a text to speech feature which reads all text in the current open document and speaks it out load to you.
    <h3>Etelka Wide Text Pro Bold Italic</h3>
    </body>
    

    让我再解释一遍。我想按位置突出显示一个单词。

    例如,我有一个位置值(x,y)=(0625)。我想按那个位置提取第一个单词(假设在那个位置我们有单词“World”),然后如何突出显示这个单词?

    编辑:

    1 回复  |  直到 16 年前
        1
  •  2
  •   Andy E    16 年前

    我能想到的唯一方法是将每个单词包装在span元素中,然后使用 document.elementFromPoint(x,y)

    function highlightWordAtXY(x, y) {
        // Get the element containing the text
        var par = document.elementFromPoint(x, y),
            // textContent or innerText ?
            t = "textContent" in par ? "textContent" : "innerText",
            // Get the text of the element. No pun intended on the par[t].
            text = par[t],
            result;
    
        // Wrap a span around every word
        par.innerHTML = text.replace(/\b(\w+)\b/g, "<span>$1</span>");
    
        // Get the elementFromPoint again, should be a span this time
        result = document.elementFromPoint(x, y);
    
        // Check that we actually clicked on a word
        if (result == par)
            return false;
    
        // Wrap HTML text around the text at x, y
        result[t] = '<span class="highlight">' + result[t] + '</span>';
    
        // Restore the content with the wrapped text
        par.innerHTML = par[t];
    }
    

    示例 http://jsfiddle.net/BSHYp/1/show/light/ -单击一个单词并观看它高亮显示。

    这里有一些重要的注意事项:

    • 每个文本块必须包装在一个元素中(例如 <p> 或 <div> <p> 不管怎样,
    • 给定位置(x,y)的元素中只能有文本, . 具有同级HTML元素的文本节点将被删除(例如,在中单击“某些”或“此处”) Some <b>text</b> here 将删除 <b> 标签)。把它们分开 <span> 元素将是唯一的解决方案,而无需构建更复杂的例程,
    • 如果您尝试将块级元素添加到 <p> 标签,
    • 在非常非常大的文本块上,您可能会遇到性能问题。在合适的地方把它们分开。