L
L
Lolo Penguin2020-05-11 13:32:21
JavaScript
Lolo Penguin, 2020-05-11 13:32:21

How to center popup block on selected text?

I am writing a text editor, and my task is to make a pop-up block in the center of the selected text, something like this:

5eb929997e356275521849.jpeg

I have a script:

var sel = document.selection, range;
    var top = 0, left = 0;


        // основные браузеры
        if (window.getSelection) {
            sel = window.getSelection();
            if (sel.rangeCount) {
                range = sel.getRangeAt(0).cloneRange();
                if (range.getClientRects()) {
                    range.collapse(true);
                    let rect = range.getClientRects()[0];
                    // var rect = range.getBoundingClientRect()[0];

                    alert(rect.width);
                    left = rect.left;
                    top = rect.top;
                    // width = rect.width;
                }
            }
        }
        

        // для IE
         else if (sel) {
             if (sel.type != "Control") {
                 range = sel.createRange();
                 range.collapse(true);
                 left = range.boundingLeft;
                 top = range.boundingTop;
             }
         }

        // получение координат
        var coords = { top:top, left:left, };


Next, using the script, I place the block at x and y coordinates.
But it places "menu" only from the right edge. Who knows how to center the selected text "menu"?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
D
Dubolom Unicellular, 2020-05-11
@duboloms

Divide your text position value by 2, something like this:

left = rect.left / 2;
top = rect.top / 2;

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question