如何突出显示给定坐标的单词

时间:2014-08-27 14:30:29

标签: javascript jquery html coordinates

我找到了这段代码:(result of the script):

HTML

<p>Each word will be wrapped in a span.</p><p>A second paragraph here.</p>Word: <span id="word"></span>

JAVASCRIPT

// wrap words in spans
$('p').each(function() {
    var $this = $(this);
    $this.html($this.text().replace(/\b(\w+)\b/g, "<span>$1</span>"));
});


// bind to each span
$('p span').hover(
    function() { $('#word').text($(this).css('background-color','#ffff66').text()); },
    function() { $('#word').text(''); $(this).css('background-color',''); }
);

我想要类似的东西。我需要做的是获得相同的结果,但不是突出显示光标下的单词(span标签),而是需要在给定坐标(以像素为单位)的情况下突出显示单词(span标签)。 有谁知道这是否可行,我该怎么办?或者还有另一种方式吗?

谢谢!

2 个答案:

答案 0 :(得分:2)

也许你想使用elementFromPoint()。它使用起来非常简单,你需要传递坐标,这个函数将返回一个元素。

对于您的特定情况,每个字必须位于独立元素spandiv或其他任何内容中。

请参阅工作示例:jsfiddle

也许你想要做一些更健壮的解决方案,如果在给定的坐标中没有元素(elementFromPoint()返回其祖先或body元素,或者如果坐标不是,则添加条件在可见部分)

答案 1 :(得分:2)

一旦每个单词标记包含在跨度中,这相对容易。您可以使用jQuery的.position().width().height()函数来确定元素是否与给定的x,y坐标集重叠。

这样简单
var x = 100, y = 100;

$("span.token").filter(function () {
    var $this = $(this), pos = $this.position();

    return y >= pos.top && y <= pos.top + $this.height() && 
        x >= pos.left && x <= pos.left + $this.width();
})

找到位置100,100处的元素。


然而。你的&#34;包裹在跨度&#34;功能错误,有潜在危险。它必须重写为更复杂但更安全的方法。

我已经创建了一个.tokenize() jQuery插件,它可以遍历DOM树,并且可以替换它找到的所有文本节点,将它们包装在HTML的可配置位中:

$.fn.extend({
    // this function recursively tokenizes all text nodes in an element
    tokenize: function (wrapIn) {
        return this.not(".tokenized").each(function () {
            $(this).addClass("tokenized").children().tokenize(wrapIn);
            $(this).contents().each(function () {
                var node = this,
                    parent = this.parentNode,
                    tokens, tokenCount;

                // text node: tokenize, dissolve into elements, remove original text node
                if (node.nodeType === 3) {
                    tokens = $(node).text().replace(/\s+/g, " ").split(" ");
                    tokenCount = tokens.length;
                    $.each(tokens, function (i, token) {
                        if (token > "") {
                            parent.insertBefore($(wrapIn).text(token)[0], node);
                        }
                        if (i < tokenCount - 1) {
                            parent.insertBefore(document.createTextNode(" "), node);
                        }
                    });
                    parent.removeChild(node);
                }
            });
        });
    }
});

用法:

$("p").tokenize("<span class='token'>");

在此处查看实时示例:http://jsfiddle.net/u5Lx6e2a/