简体   繁体   English

javascript选择/范围坐标

[英]javascript selection/range coordinates

I would like to absolute-position a div on either the initial or terminal corner of a text selection, as the user drags their mouse along. 当用户拖动鼠标时,我想在文本选择的初始或终端角上绝对定位div。 Unfortunately, Range only provides the index position, not the x/y coordinates. 不幸的是,Range只提供索引位置,而不是x / y坐标。 I think there might be a way to do this with range.insertNode, but only for one side. 我认为可能有一种方法可以使用range.insertNode,但仅限于一方。 (This might also help someone position an auto-complete box under a contenteditable.) (这也可能有助于某人在满足的情况下定位一个自动完成的盒子。)

How can I get the x/y coordinates of a text selection, or of the text cursor? 如何获取文本选择或文本光标的x / y坐标?

Works in chrome/webkit, positioning the div after the last-selected letter. 在chrome / webkit中工作,在最后选择的字母后面定位div。 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>

You would have to get the mouse position from the mouse move event. 您必须从鼠标移动事件中获取鼠标位置。 Then you can get the position of the text input element and do the math (make the mouse position relative). 然后你可以得到文本输入元素的位置并进行数学运算(使鼠标位置相对)。

EDIT: 编辑:

Here is a page where you can get JavaScript code that will get the caret position in pixels. 这是一个页面 ,您可以在其中获取将以像素为单位获取插入位置的JavaScript代码。

If you want to use JQuery, you can use this 如果你想使用JQuery,你可以使用

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM