我想实现内联版本,因此如果用户点击带有一些文本的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)
});
答案 0 :(得分:1)
看起来你可以这样做:
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,而选择/范围模型则完全不同。
答案 1 :(得分:0)
我找到了解决方案:
JS:
function getCaretPosition(editableDiv) {
var caretPos = 0, containerEl = null, sel, range;
if (window.getSelection) {
sel = window.getSelection();
if (sel.rangeCount) {
range = sel.getRangeAt(0);
if (range.commonAncestorContainer.parentNode == editableDiv) {
caretPos = range.endOffset;
}
}
} else if (document.selection && document.selection.createRange) {
range = document.selection.createRange();
if (range.parentElement() == editableDiv) {
var tempEl = document.createElement("span");
editableDiv.insertBefore(tempEl, editableDiv.firstChild);
var tempRange = range.duplicate();
tempRange.moveToElementText(tempEl);
tempRange.setEndPoint("EndToEnd", range);
caretPos = tempRange.text.length;
}
}
return caretPos;
}
$.fn.selectRange = function (start, end) {
if (!end) end = start;
return this.each(function () {
if (this.setSelectionRange) {
this.focus();
this.setSelectionRange(start, end);
} else if (this.createTextRange) {
var range = this.createTextRange();
range.collapse(true);
range.moveEnd('character', end);
range.moveStart('character', start);
range.select();
}
});
};
用法:
$('#content').click(function (e) {
var content = $(this);
var editor = $('#editor');
var caret = getCaretPosition(this);
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)
editor.selectRange(caret, caret);
});