【发布时间】:2013-07-31 08:32:19
【问题描述】:
我想实现内联编辑,所以如果用户单击带有一些文本的 div,textarea 将出现在与单击 div 的位置相同的位置,并从 div 中获取文本。这对我来说很好,但我接下来要做的是根据 div click 事件的 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>
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)
});
【问题讨论】:
-
插入符号始终定位在文本节点上,您不能将其定位到空白区域。
-
该区域不会为空 - 它将具有与 div 相同的内容。
-
我认为 contenteditable 功能会导致问题,当您使用诸如 Knockout 或 Angular 之类的绑定工具时。如果您查看一些流行的任务管理工具,例如 wunderlist.com 或 asana.com,它们并不使用 contenteditable。
-
为什么会有这些缺点?这个问题有什么问题吗?
标签: javascript html textarea