开发者

Webkit, IE deselecting text

I'm working on making a contentEditable jQuery plugin. I've created a 'tools' bar to perform actions to the text such as making it bold, italics etc using execCommand. The problem is that when you select text and click one of the buttons (divs with onclick events) it deselects the text you had selected (all browsers). To fix this I have used:

toolBar.onmousedown=function(){return false};

Which works well in Firefox and Opera. I'm trying to use

toolBar.onselectstart = fu开发者_Python百科nction(){return false};

which prevents text selection in IE. However, neither webkit or IE work. I've seen this done with input buttons before, but I'd rather use divs. Any ideas?


A simple alternative is to use <button> tags for your toolbar. That way it doesn't lose the text selection in the first place.


I solved this problem by reselecting the text.

On mouseup I capture the selection information:

$.getSelection = function() {
    // ie has its own way of doing things from here on.
    if($.browser.msie) return document.selection.createRange();

    if (window.getSelection) {
        var selection = window.getSelection();
    }
    else if (document.selection) { // should come last; Opera!
        var selection = document.selection.createRange();
    }

    if (selection.getRangeAt)
        var range = selection.getRangeAt(0);
    else { // Safari!
        var range = document.createRange();
        range.setStart(selection.anchorNode, selection.anchorOffset);
        range.setEnd(selection.focusNode, selection.focusOffset);
    }
    if (!range.toString().match(/[^\t\r\n ]/)) return false;

    var ret = {};

    // start end length text

    ret.startContainer  = range.startContainer;
    ret.start   = range.startOffset;
    ret.endContainer    = range.endContainer;
    ret.end     = range.endOffset;
    ret.length = ret.end - ret.start;
    ret.collapsed   = range.collapsed;

    return ret;
};

This is stored somewhere of your choosing.

I then either reselect the text if the browser is w3c compliant for DOM Range (i.e. all but ie) and perform the execCommand:

function handleReselection() {
    if($.browser.msie) {
        return this.selection;
    }
    else {
        setSelection(this.selection);
        return document
    }
}

function setSelection(selection) {
    var sel = window.getSelection();
    sel.removeAllRanges();
    var range = document.createRange();
    range.setStart(selection.startContainer, selection.start);
    range.setEnd(selection.endContainer, selection.end);
    sel.addRange(range);
}

handleReselection().execCommand('bold', false, null);
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜