2

样本

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

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

4

2 回答 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

于 2012-08-15T08:48:56.910 回答
1

我已经深入研究了 Rangy 的代码(太棒了!但是将其完全包含在我的用例中有点过头了),只要有人不需要完全的跨浏览器兼容性,她就可以使用本机单线:

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

然后你将有可用top的 , bottom,rightlefton pos (好吧,我撒谎了——不是真正的单线,它必须被包装以检查是否有一些范围)。

我只需要它与 Firefox 一起工作,所以对我来说就足够了。

概括:

  • 完全在 Firefox 17 / Chrome 23 中工作(也可用于跟踪插入符号,无需实际选择,也无需启用插入符号浏览)
  • 但是请注意,当您单击页面的空白片段(而不是任何文本)时, 您实际上会将插入符号移动到某处(启用插入符号浏览 -F7在 Firefox 中 - 以查看位置)。当您在段落之间单击时,它通常是段落的结尾——如果您单击它旁边,或者光标上方最接近的文本。
  • 在 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>
于 2012-11-30T00:30:34.973 回答