开发者

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. 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> i开发者_开发问答nto 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 :)


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 (\u00A0 or &nbsp; in HTML) inside your placeholder element. You may want to remove the placeholder in focusOnPlaceholder() after selecting the range.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜