iframe Ie下光标定位问题

在IE下 对iframe编辑器js使用

var ifr = document.getElementById('ifr');

var sRange=doc.selection.createRange();
sRange.execCommand('insertimage',false,image_src);

来插入图片,图片总是插入在编辑器的前面,于是查找问题,偶然在一篇博客中知道了原因(具体地址疏忽没记下来)

原因是 在IE下 当光标在框中消失,在进行插入的时候,会回到起始位置(因为要显示正在加载的提示图片导致光标消失)

所以会把图插入到前面,下面是资料中提供的方法:

    /**
     * 记录IE的编辑光标
     */
    document.getElementById('ifr').contentWindow.document.onbeforedeactivate =function(){
        var contentWindow = document.getElementById('ifr').contentWindow;
        var range = contentWindow.document.selection.createRange();
        ieSelectionBookmark = range.getBookmark();
    };

    /**
      * 复位IE的编辑光标
      */
    if(ieSelectionBookmark){
         var contentWindow = document.getElementById('ifr').contentWindow;
         var range = doc.body.createTextRange();
         range.moveToBookmark(ieSelectionBookmark);
         range.select();
         ieSelectionBookmark = null;
    };

复位的时候一定要在插入图片之前,下面记录下 兼容ie ff的iframe插入内容方法:

var ifr = document.getElementById('ifr');
$('#sms_loading').hide();

if(browser_type == 'ie'){

ifr.contentWindow.focus();
var doc = ifr.contentDocument || ifr.contentWindow.document;

var sRange=doc.selection.createRange();

sRange.execCommand('insertimage',false,response.showpic);

}else{

ifr.focus();

var rng = ifr.contentWindow.getSelection().getRangeAt(0);

var frg = rng.createContextualFragment(response.showpic);

ifr.contentWindow.document.execCommand('insertimage',false,response.showpic);

}

其中关于execCommand方法的使用,网上有很多例子随意百度下即可。

2014-11-11

原文地址:https://www.cnblogs.com/still-love-you/p/4660380.html