将光标移动到 contentEditable DIV 中的占位符元素
我有一个 contentEditable DIV,当用户按下某个键时,底层代码将被处理并被更新的代码替换。唉,这会导致光标位置丢失。
但是,为了保留光标位置,在处理开始之前,我成功地将 插入到 DIV 的正确位置。这保留了光标的预期位置,但现在我似乎无法设置范围来选择它。
这就是我目前所拥有的:
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();
}
}
任何帮助将不胜感激,跨浏览器解决方案将是令人难以置信的:)
I have a contentEditable DIV and, when the user presses a key, the underlying code is processed and replaced by updated code. 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. 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 :)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
跨浏览器解决方案是使用我的 Rangy 库,特别是 选择保存/恢复模块,它使用类似的占位符技术并且经过了充分测试。但是,这可能可以在不使用库的情况下通过在内部放置一些内容(例如,不间断的空格(HTML 中的
)来解决)您的占位符元素。您可能需要在选择范围后删除
\u00A0
或focusOnPlaceholder()
中的占位符。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. However, this can probably be fixed without using a library by putting some content (for example, a non-breaking space (
in HTML) inside your placeholder element. You may want to remove the placeholder in
\u00A0
orfocusOnPlaceholder()
after selecting the range.