Get selected text position and place an element next to it

前端 未结 3 1424
挽巷
挽巷 2020-11-27 02:49

tl;dr

The idea is to allow a user to mark any text and see menu pop-up just next to the selection, with possible actions to apply to the selected text.


<
3条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-11-27 03:06

    I use getBoundingClientRect() when I need the content to remain undisturbed, while placing additional content near it.

        var r=window.getSelection().getRangeAt(0).getBoundingClientRect();
        var relative=document.body.parentNode.getBoundingClientRect();
        ele.style.top =(r.bottom -relative.top)+'px';//this will place ele below the selection
        ele.style.right=-(r.right-relative.right)+'px';//this will align the right edges together
    

    this works in Chrome, but IE likes to give weird things, so here's a cross-browser solution: (Tested in Chrome and IE, probably works elsewhere)

    https://jsfiddle.net/joktrpkz/7/

提交回复
热议问题