How to have a popup after selecting text?

前端 未结 5 835
天命终不由人
天命终不由人 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 02:57

    jQuery isn't going to be of much use here, so you'll need pure JS to do the selection grabbing part (credit goes to this page):

    function getSelected() {
      if(window.getSelection) { return window.getSelection(); }
      else if(document.getSelection) { return document.getSelection(); }
      else {
        var selection = document.selection && document.selection.createRange();
        if(selection.text) { return selection.text; }
        return false;
      }
      return false;
    }
    

    You were on the right track with the mouseup handler, so here's what I got working:

    $('#test').mouseup(function() {
        var selection = getSelected();
    
        if (selection) {
            alert(selection);
        }
    });
    

    And a live demo: http://jsfiddle.net/PQbb7/7/.

提交回复
热议问题