在IE10中使用execCommand插入后如何模糊(焦点丢失)图像

How blur (focus lost) the image after insertion with execCommand in IE10?

本文关键字:模糊 焦点 图像 何模糊 IE10 execCommand 插入      更新时间:2023-09-26

我有一个内容可编辑的DIV,例如:

<div contenteditable='true' id='myRichTextBox'></div>

此外,我还有一个按钮,可以将图像插入到提到的DIV中。一旦插入图像,它就使用可调整大小的处理程序进行聚焦
我如何才能失去它的焦点并将焦点恢复到内容可编辑的DIV

<button type='button' onclick='insertImage()'>Insert an image</button>

Javascript代码:

function insertImage()
{
document.execCommand('insertImage',false,'myImage.png');
}

感谢您的帮助

您可以通过多种方式解决这一问题,但一个简单的方法是在大多数浏览器中使用document.execCommand("InsertHTML"),在IE中返回到pasteHTML()。但是,这在IE 11中不起作用,因为它不支持document.selectionInsertHTML命令。

function insertImageWithInsertHtml(imgSrc) {
    var imgHtml = "<img src='" + imgSrc + "'>";
    var sel;
    if (document.queryCommandSupported("InsertHTML")) {
        document.execCommand("InsertHTML", false, imgHtml);
    } else if ( (sel = document.selection) && sel.type != "Control") {
        var range = sel.createRange();
        range.pasteHTML(imgHtml);
        range.collapse(false);
        range.select();
    }
}

另一种在除IE<=8(您可以使用与上述相同的回退)将是使用从选择中获得的范围的insertNode()方法手动插入图像。这是最经得起未来考验和符合标准的方法,所以我建议:

function insertImageWithInsertNode(imgSrc) {
    var sel;
    if (window.getSelection) {
        var sel = window.getSelection();
        if (sel.rangeCount > 0) {
            var range = sel.getRangeAt(0).cloneRange();
            range.deleteContents();
            var img = document.createElement("img");
            img.src = imgSrc;
            range.insertNode(img);
            // Place the caret immediately after the image
            range.setStartAfter(img);
            range.collapse(true);
            sel.removeAllRanges();
            sel.addRange(range);
        }
    } else if ( (sel = document.selection) && sel.type != "Control") {
        var range = sel.createRange();
        range.pasteHTML("<img src='" + imgSrc + "'>");
        range.collapse(false);
        range.select();
    }
}

最后,这里有一个展示所有三种技术的现场演示:

http://jsfiddle.net/timdown/9ScLA/3/

我使用了以下解决方案并成功了!

function insertImage(imgSrc)
{
    var ua = navigator.userAgent.toLowerCase();
    var tr;
    if (ua.indexOf("msie") > 0)
        tr = document.selection.createRange();
    document.execCommand("insertImage", false, imgSrc);
    if(ua.indexOf("firefox") > 0)
        document.execCommand("enableObjectResizing", false, false);
    if (ua.indexOf("msie") > 0)
    {
        tr.collapse(false);
        tr.select();
    }
    this.textbox.focus();
}