How to have a popup after selecting text?

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

    You need a event listener that listen to mouseup event.

    var bubbleDOM = document.createElement('div');
    bubbleDOM.setAttribute('class', 'selection_bubble');
    document.body.appendChild(bubbleDOM);
    
    // Lets listen to mouseup DOM events.
    document.addEventListener('mouseup', function (e) {
      var selection = window.getSelection().toString();
      if (selection.length > 0) {
        renderBubble(selection);
      }
    }, false);
    
    // Close the bubble when we click on the screen.
    document.addEventListener('mousedown', function (e) {
      bubbleDOM.style.visibility = 'hidden';
    }, false);
    
    // Move that bubble to the appropriate location.
    function renderBubble(selection) {
      bubbleDOM.innerHTML = selection;
      bubbleDOM.style.visibility = 'visible';
    }
    

提交回复
热议问题