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

时间:2010-08-04 11:00:50

标签: javascript dom html dhtml

示例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>

例如 - &gt; “general”(在**之间)是x = 0且y = 465。我知道x,y的位置。但如何突出显示位于特定位置的单词?

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

例如我有一个位置值(x,y)=(0,625)。我想在那个位置提取第一个单词(假设 - 在那个位置 - 我们有单词“世界”)然后如何突出显示该单词?

编辑:
这里Y坐标是整个html文档的绝对位置。

1 个答案:

答案 0 :(得分:2)

我能想到的唯一方法是在span元素中包装每个单词,然后使用document.elementFromPoint(x,y)来获取给定位置的span元素。像这样:

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元素。具有兄弟HTML元素的文本节点将删除它们(例如,点击Some <b>text</b> here中的“部分”或“此处”将删除<b>标记。将它们分成单独的<span>元素将是唯一的解决方案,而无需构建更复杂的例程,
  • 如果您尝试将块级元素添加到<p>标记,IE将抛出“未知运行时错误”,
  • 在非常非常非常大的文本块上,您可能会遇到性能问题。在适当的地方分解它们。