开发者

Finding the textNode which the cursor is currently over

开发者 https://www.devze.com 2023-01-02 11:00 出处:网络
Let\'s say I have the following... <div id=\"text\">Some text</div> When my mouse goes over Some, Some will be returned an开发者_如何学JAVAd the same with text.

Let's say I have the following...

<div id="text">Some text</div>

When my mouse goes over Some, Some will be returned an开发者_如何学JAVAd the same with text.

Is this possible without putting each node into it's own element?


That is pretty much impossible. Since in Javascript you just know that you are hovering over an element (div and/or a textnode in this case), you can't know which word is hovered just like that.

Maybe with alot of effort and some geeky hacks on offsets and/or event.pageX/Y, but I would go for the solution you mentioned yourself, wrapping each word into its own element.

var $text = $('#text');
$text.html($text.text().replace(/\b(\w+)\b/g, "<span class='word'>$1</span>"));

$('.word').bind('mouseenter', function(e){
   alert($(this).text());
});


This isn't possible without either wrapping the two nodes in elements or somehow determining the exact position of the text nodes and then binding to some parent's click event. The former option is simpler. Just wrap them in spans:

<div id="text"><span>Some<span> <span>text</span></div>

Or, if you need to wrap them all automatically:

jQuery.fn.getTextNodes = function(){
    return this.not('script').contents().map(function(){
        var n = this.nodeType;
        return n === 3 ? this : n === 1 ? jQuery(this).getTextNodes().get() : [];
    });
};

jQuery('#text').getTextNodes().replaceWith(function(){
    return jQuery(this.data.replace(/\S+/g, '<span>$&</span>')).filter('span').click(function(){
        alert('You just clicked on the word: ' + jQuery.text([this]));
    }).end();
});​ ​

Demo: http://jsfiddle.net/PYKqM/

0

精彩评论

暂无评论...
验证码 换一张
取 消