Detect hover on selected text

后端 未结 2 2026
伪装坚强ぢ
伪装坚强ぢ 2021-02-03 11:22

I am building a WYSIWYG rich text editor.

When the user selects a portion of his/her text, I would like to present a menu in a tooltip. Presenting the menu works fine bu

2条回答
  •  醉酒成梦
    2021-02-03 11:45

    On mouseup, use Range.getClientRects to grab the bounding rectangles of each line of the selection.

    You can then test if the mouse is over the selection like this:

    var cr= [];
    
    $(document).on({
      'mouseup': function() {
        cr= window.getSelection().getRangeAt(0).getClientRects();
      },
      'mousemove': function(ev) {
        //hide the pop up
        for(var i = 0 ; i < cr.length ; i++) {
          if(ev.pageX >= cr[i].left && ev.pageX <= cr[i].right &&
             ev.pageY >= cr[i].top  && ev.pageY <= cr[i].bottom
            ) {
            //show the pop up
            break;
          }
        }
      }
    });
    

    Fiddle

提交回复
热议问题