开发者

Preserve text selection in contenteditable while interacting with jQuery UI Dialog and text input

I have a jQuery dialog for making links in a contentEditable span. The problem is that clicking a button to open the dialog causes the selection to be lost, text input inside the dialog also causes the selection to be lost.

I can fix the button with -moz-user-select:none; but -webkit-user-select:none doesn't work in Chrome.

I can fix the input by wrapping it in an iframe, but that's messy and clicking anywhere else also kills the selection, for example, dragging the dialog around.

I've seen the solution at How to preserve text select开发者_如何学Pythonion when opening a jQuery dialog, but that doesn't work in many browsers in a contenteditable element, only real inputs.

Is there a nice solution to my problem?


You could save and restore the selection using simple functions such as the following when the dialog is opened and closed. I am not familiar enough with jQuery dialogs to know the mechanism for hooking into the dialog opening and closing. The first, saveSelection, returns you a Range or TextRange object that you should store in a variable which you later pass to restoreSelection:

function saveSelection() {
    if (window.getSelection) {
        sel = window.getSelection();
        if (sel.getRangeAt && sel.rangeCount) {
            return sel.getRangeAt(0);
        }
    } else if (document.selection && document.selection.createRange) {
        return document.selection.createRange();
    }
    return null;
}

function restoreSelection(range) {
    if (range) {
        if (window.getSelection) {
            sel = window.getSelection();
            sel.removeAllRanges();
            sel.addRange(range);
        } else if (document.selection && range.select) {
            range.select();
        }
    }
}
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜