Javascript selection / range coordinates

I would like to set the absolute position of the div at the start or end corner of the text selection when the user drags them with the mouse. Unfortunately, Range only provides index position, not x / y coordinates. I think there may be a way to do this with range.insertNode, but only for one side. (It can also help someone put an autocomplete field under content accessibility.)

How to get x / y coordinates for selecting text or text cursor?

+3
source share
2 answers

Works in chrome / webkit, positioning the div after the last selected letter. Usually.

<html><head>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script>
<script>
var $div;
var last;
function find() {
    var selection = window.getSelection();
    var text = selection.toString();
    if (last==text) return; else last=text; // prevent needless computations if no changes to selection
    if (selection.rangeCount==0) return;

    var range = selection.getRangeAt(0);
    var $span= $("<span/>");

    newRange = document.createRange();
    newRange.setStart(selection.focusNode, range.endOffset);
    newRange.insertNode($span[0]); // using 'range' here instead of newRange unselects or causes flicker on chrome/webkit

    var x = $span.offset().left;
    var y = $span.offset().top;
    $div.text(x+" "+y);
    $div.css({left:x,top:y+($div.height())});
    $span.remove();
}
$(window).load(function() {
    $("body").keydown(function(e) {
        //find();
        setTimeout(find,0);
    });
    $("body").mousemove(function(e) {
        //find();
        setTimeout(find,0);
    });
    $div=$("<div style='border:1px solid red;background:white; position:absolute;'>").appendTo($("body"));
});
</script>
</head>
<body><p>the quick brown fox</p><ul><li>jumps <i>over</i></li></ul><p>the lazy dog</p></body>
</html>
+6
source

. ( ).

EDIT:

, JavaScript, .

JQuery, this

0

Source: https://habr.com/ru/post/1727827/


All Articles