how refocus when insert image in contenteditable D

2019-08-11 13:02发布

问题:

There is a div: <div contenteditable="true"></div> in IE(7,8,9), then I click a button to insert an image with using the document.execCommand('insertImage') method. Then the image was inserted. Until now there is no problem. But the inserted image is selected with resizable handlers. How could I cancel the selection and refocus behind the image? Thanks.

$button.click(function(){ document.execCommand("insertImage",false,'url'); });

回答1:

Updated with simpler code

Here's some nasty code to do this. In other browsers, it seems to work anyway, so the following can be used as it is.

Demo: http://jsfiddle.net/timdown/mr7Ac/6/

Code:

function insertImage() {
    var sel = document.selection;
    if (sel) {
        var textRange = sel.createRange();
        document.execCommand('insertImage', false, "someimage.png");
        textRange.collapse(false);
        textRange.select();
    } else {
        document.execCommand('insertImage', false, "someimage.png");
    }
}


回答2:

Try something like this (IE only):

function insertImage(){
    if(document.selection){
        var sel=document.selection;
        var range=sel.createRange();
        var amount=(document.addEventListener)?2:1;
        document.execCommand('insertImage', false, 'url');
        range.move('character',amount);
        range.select();
    }
    return;
}