How to have a popup after selecting text?

前端 未结 5 883
天命终不由人
天命终不由人 2021-02-06 02:12

I can\'t seem to figure this out. I have a div with some text in it. When the user selects pieces of it (totally at random, whatever they want), I want a small popup to occur

5条回答
  •  轮回少年
    2021-02-06 03:13

    You can get it from the base DOM element likeso:

    var start = $('#textdiv')[0].selectionStart;
    var end = $('#textdiv')[0].selectionEnd;
    var highlight = $('#textdiv').val().substring(start, end);
    // Note the [0] part because we want the actual DOM element, not the jQuery object
    

    At this point, you just need to bind it to a click event. I think in this case mouseup is the event you'd want to bind to, since a user clicks and holds the mouse and then releases it after they're done highlighting text.

    The problem is this would not trigger users that use only the keyboard to highlight text. For that you'd want to use keyup on the element and filter for the right keystrokes.

提交回复
热议问题