[英]Move cursor to placeholder element in a contentEditable DIV
I have a contentEditable DIV and, when the user presses a key, the underlying code is processed and replaced by updated code. 我有一个contentEditable DIV,当用户按下一个键时,底层代码被处理并被更新的代码替换。 Alas, this causes the cursor position to be lost.
唉,这会导致光标位置丢失。
However, in order to preserve the cursor position, I am successfully inserting a <span id="placeholder"></span>
into the DIV at the correct position before processing begins. 但是,为了保留光标位置,我在处理开始之前成功地将
<span id="placeholder"></span>
插入DIV中的正确位置。 This preserves the cursor's intended position, but now I can't seem to set the range to select it. 这保留了光标的预期位置,但现在我似乎无法设置范围来选择它。
Here's what I currently have: 这是我现在拥有的:
function focusOnPlaceholder() {
var placeholder = document.getElementById('placeholder');
if( !placeholder ) return;
var sel, range;
if (window.getSelection && document.createRange) {
range = document.createRange();
range.selectNodeContents(placeholder);
range.collapse(true);
sel = window.getSelection();
sel.removeAllRanges();
sel.addRange(range);
} else if (document.body.createTextRange) {
range = document.body.createTextRange();
range.moveToElementText(placeholder);
range.select();
}
}
Any help would be appreciated, and a cross-browser solution would be incredible :) 任何帮助将不胜感激,跨浏览器解决方案将是令人难以置信的:)
A cross-browser solution would be to use my Rangy library and specifically the selection save/restore module , which uses a similar placeholder technique and is well tested. 跨浏览器的解决方案是使用我的Rangy库,特别是选择保存/恢复模块 ,它使用类似的占位符技术并经过充分测试。 However, this can probably be fixed without using a library by putting some content (for example, a non-breaking space (
\
or
in HTML) inside your placeholder element. You may want to remove the placeholder in focusOnPlaceholder()
after selecting the range. 然而,这或许可以被固定,而无需使用库通过把一些内容(例如,一个不间断空格(
\
或
您的占位符元素中的HTML),您可能需要删除的占位符focusOnPlaceholder()
后选择范围。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.