使用 x 和 y 位置设置文本区域的插入符位置

cry*_*yss 5 html javascript textarea

我想实现内联版本,因此如果用户单击带有某些文本的 div,文本区域将出现在与单击的 div 位置相同的位置,并从 div 获取文本。这对我来说很好,但我接下来要做的是根据 div 单击事件的 x 和 y 位置设置 textarea 的插入符位置。有任何想法吗?

HTML:

<div id="content" style="display: block; z-index: 10">Some text</div>

<textarea id="editor" style="position: absolute; display: none; z-index: 11"></textarea>
Run Code Online (Sandbox Code Playgroud)

JS:

$('#content').click(function(e) {
    var content = $(this);
    var editor = $('#editor');

    var position = content.offset();

    editor.css('left', position.left);
    editor.css('top', position.top);
    editor.val(content.text());
    editor.show();

    var mousePosition = { x: e.offsetX, y: e.offsetY };

    // here I want to set the #editor caret position at the same place,
    // where user clicks the #content (mousePosition variable)
});
Run Code Online (Sandbox Code Playgroud)

Tee*_*emu 4

看起来你可以做这样的事情:

createTextArea = function (e) {
    var range = window.getSelection().getRangeAt(0),
        start = range.startOffset,
        target = e.target,
        setPoint;
    while (target.tagName.toLowerCase() !== 'div') {
        target = target.parentElement;
        if (!target) return;
    }
    range.setStart(target, 0);
    setPoint = range.toString().length;
    // place and show #editor
    editor.focus();
    editor.setSelectionRange(setPoint, setPoint);
    return;
};
Run Code Online (Sandbox Code Playgroud)

jsFiddle 中的示例。请注意,这仅适用于现代浏览器。较旧的 IE 没有输入 API,并且选择/范围模型完全不同。