javascript - Get cursor position in selection - relative to document - Stack Overflow

SampleThis is some text in an editable div. This can span over multiple lines, paragraphs and so on a

Sample

This is some text in an editable div. This can span over multiple lines, paragraphs and so on and so forth. What I want to do is find the relative position of the caret right here. Meaning, the caret is positioned {top:'5px', left:'250px'}, relative to the div or the document.

The idea is to then provide drop downs with options. Is this possible directly or will I have to concoct a solution based on the div line-height, padding,.. + caret position etc?

Sample

This is some text in an editable div. This can span over multiple lines, paragraphs and so on and so forth. What I want to do is find the relative position of the caret right here. Meaning, the caret is positioned {top:'5px', left:'250px'}, relative to the div or the document.

The idea is to then provide drop downs with options. Is this possible directly or will I have to concoct a solution based on the div line-height, padding,.. + caret position etc?

Share Improve this question asked Aug 15, 2012 at 8:44 Jibi AbrahamJibi Abraham 4,6962 gold badges33 silver badges60 bronze badges
Add a ment  | 

2 Answers 2

Reset to default 5

Check this demo from rangy. Maybe just what you are looking for:

https://github./timdown/rangy/blob/master/demos/position.html

If you look at the code, you'll be able to see this:

var startPos = rangy.getSelection().getStartDocumentPos(); // get x, y of selection/cursor

and then you can use startPos.x and startPos.y

I've dug through the code of Rangy (it's awesome! but an overkill to include it wholly in my use case), and as long as someone doesn't need full cross-browser patibility, she may use a native one-liner:

var pos = window.getSelection().getRangeAt(0).getClientRects()[0]

and then you'll have available top, bottom, right and left on pos (okay, I lied - not a truly one-liner, it has to be wrapped to check if there's some range).

I just need it to work with Firefox so it's enough for me.

Summary:

  • Works fully in Firefox 17 / Chrome 23 (also for just tracking the caret, without having real selection, and without having to enable caret browsing)
  • Note however that when you click on an empty fragment of the page (not on any text), you will in fact move the caret somewhere (enable caret browsing -- F7 in Firefox -- to see where). It's usually end of paragraph -- if you click next to it, or the closest text just above the cursor -- when you click between the paragraphs.
  • In Opera 12, works only if there's a non-empty selection.
  • Doesn't work on IE8, haven't checked on IE9 nor IE10.

Demo (doesn't work on JSFiddle, so I dump it here in entirety):

<!DOCTYPE html>
<head>
    <script type="text/javascript">
    var getSelectionTopLeft = function (){
        var selection = window.getSelection();
        var rangePos, x, y;
        if(selection.rangeCount) {
            rangePos = window.getSelection().getRangeAt(0).getClientRects()[0];
            // you can get also right and bottom here if you like
            x = parseInt(rangePos.left);
            y = parseInt(rangePos.top);
            console && console.log("found selection at: x=" + x + ", y=" + y);
        }else{
            x = 0;
            y = 0;
            console && console.log("no selections found");
        }
        return {x: x, y: y};
    }
    var move = function (offsetX, offsetY){
        var coords = getSelectionTopLeft();
        var square = document.getElementById('square');
        square.style.left = (coords.x + offsetX) + 'px';
        square.style.top = (coords.y + offsetY) + 'px';
    }
    </script>
    <style type="text/css">
    #square {position:absolute; top:0; left:0; width:10px; height:10px; background-color:red;}
    </style>
</head>

<body>
    <h1>Caret position test</h1>
    <div id="square"></div>
    <button onclick="move(5, 5)">move the square 5px/5px below the caret</button>

    <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit.
    Curabitur tempor pharetra iaculis. Ut tempor mauris et ligula
    aliquam sed venenatis dui pharetra. Duis dictum rutrum venenatis.
    Cras ut lorem justo.</p>

    <p>Nam vehicula elit tincidunt nibh elementum venenatis. Duis a facilisis sem.
    Morbi luctus porttitor feugiat. Nunc feugiat augue eu tortor interdum fermentum
    a tincidunt felis.</p>
</body>
</html>

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1745280208a4620242.html

相关推荐

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信