开发者

How can I get the text that was clicked on in Javascript?

Does anyone know if it is possible with javascript to to tell the position of a mouse click in some text? I know it's easy to get the x,y coordinates, but I'm wanting the position in the text.

For example if I clicked inside <p>foo bar</p> I want to be able to tell that the click was on/after the 5th character. Or that foo b is before the click and ar is after it.

By the way, I'm using jQuery too, I'm happy with pure JS and sol开发者_StackOverflow中文版utions that use jQ.

Thanks in advance.


Javascript and browsers don't support this directly, but you could technically wrap each character in a span and do it based on which span was clicked on:

<p>
    <span>f</span>
    <span>o</span>
    <span>o</span>
    <span> </span>
    <span>b</span>
    <span>a</span>
    <span>r</span>
</p>

If anybody actually tries this, be prepared to be eaten by a velociraptor :p


Expanding on codeka's answer and my comment . . . try this (i'm assuming your target p has id my_p):

(function() {
  var p = $('#my_p');
  var o_string = p.text();
  p.html('<span>' + o_string.split('').join('</span><span>') + '</span>');

  $('span', p).each(function(i) {
    $(this).data('MyIndex', i);
  }).click(function() {
    var char_index = $(this).data('MyIndex');
    if (char_index >= 5) {
      alert('You clicked after character 5!  Before: "' + o_string.substring(0, char_index) + '", After (inclusive): "' + o_string.substring(char_index) + '"');
    }
  });
})();

What that does is: 1. Find the paragraph where you need per-character clicking knowledge, 2. Split the text in that paragraph into a number of one-character spans, 3. Inform each of those one-character spans of its position in the string, and 4. Assign a click() handler to each span, which spits out the information about the span (including your example of char index >= 5, and printing the before and after parts of the string).

Of course you might want to put that in $(document).ready(...) instead of an anonymous function; I didn't know if maybe you had a precondition for activating this detection though.


Frankly I don't like very much idea of travesting text and 'span'ing it. But I'm not quite sure what you are looking for, if you need just the word clicked and do dblclick instead of click will do, i have next code:

$('*').dblclick(function(event){
    console.log((window.getSelection() || document.getSelection() || document.selection.createRange().text).toString());
    event.stopPropagation();
});

after that you can deselect text if you want. Without toString() you will get object that has a lot of properties, study it as well.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜