获取光标在选择中的位置 - 相对于文档

问题描述 投票:2回答:2

样品

这是可编辑div中的一些文本。这可以跨越多行,段落等等。我想要做的是在这里找到插入符号的相对位置。意思是,相对于div或文档,插入符号位于{top:'5px',left:'250px'}。

我们的想法是提供可选的下拉菜单。这可能是直接的,还是我必须根据div line-height, padding,.. + caret position等编制解决方案?

javascript caret
2个回答
5
投票

从rangy查看此演示。也许只是你在找什么:

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

如果您查看代码,您将能够看到:

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

然后你可以使用startPos.xstartPos.y


1
投票

我已经挖掘了Rangy的代码(这太棒了!但是将其全部包含在我的用例中是一种过度杀伤),只要有人不需要完全跨浏览器兼容性,她就可以使用本机单行:

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

然后你就可以在top上找到bottomrightleftpos(好吧,我撒了 - 不是真正的单行,它必须被包裹以检查是否有一些范围)。

我只需要它与Firefox一起工作,这对我来说已经足够了。

摘要:

  • 完全适用于Firefox 17 / Chrome 23(也可用于跟踪插入符,无需实际选择,无需启用插入符号浏览)
  • 但请注意,当您单击页面的空片段(而不是任何文本)时,您实际上会将插入符移动到某处(启用插入符号浏览 - 在Firefox中使用F7 - 以查看位置)。它通常是段落的结尾 - 如果你单击它旁边,或者在光标上方的最接近的文本 - 当你在段落之间点击时。
  • 在Opera 12中,只有在存在非空选择时才有效。
  • 在IE8上不起作用,还没有检查过IE9或IE10。

演示(不适用于JSFiddle,因此我将其全部转储):

<!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>
© www.soinside.com 2019 - 2024. All rights reserved.