gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-28 01:54:14 24 4
gpt4 key购买 nike

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

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>

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)
});

最佳答案

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

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;
};

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

关于javascript - 使用 x 和 y 位置设置文本区域的插入符号位置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17965354/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com