HTML编辑器失去焦点后在原来光标位置插入信息/图片
示例代码参考
在制作html编辑器,有些时候iframe编辑器需要失去焦点,然后进行一些处理操作,如上传图片,编辑其他的信息后将上传的图片或者编辑好的信息插入到原来html编辑器原光标的位置。
在firefox下调用focus函数可以使光标回复到原来的位置,但是IE下光标处于html编辑器的头,所以要想在原来的位置插入相关信息,需要保存range对象,然后操作完后使用range对象在原来的位置进行操作。
下面是在当编辑器获取焦点后,然后在text中输入一些信息,然后点击按钮将输入的信息插入到html编辑器原来光标的位置处。
对于插入图片也差不多,在点击某个按钮的时候先调用SaveRange函数保存range对象,在插入函数中判断是否存在range对象,内容和insert函数差不多。
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" " http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns=" http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="content-type" content="text/html;charset=gb2312" /> <title>HTML编辑失去焦点后在原来光标位置插入信息/图片--编程设计网</title> </head> <body> <br ><iframe style="width:300px;height:200px" id="editor"></iframe> <br >内容:<input type="text" id="txt" onmousedown="SaveRange()" /><input type="button" onclick="insert()" onmousedown="SaveRange()" value="插入输入的字符在HTML编辑器原位置" /> <script type="text/javascript"> var isIE=!!document.all,ieRange=false,editor,win,doc,txt; window.onload=function(){ editor=document.getElementById('editor'); win=editor.contentWindow; doc=win.document; txt=document.getElementById('txt'); doc.designMode='On';//可编辑 win.focus(); } function SaveRange(){//IE下保存Range对象 if(isIE&&!ieRange){//是否IE并且判断是否保存过Range对象 var sel=doc.selection; ieRange=sel.createRange(); if(sel.type!='Control'){//选择的不是对象 var p=ieRange.parentElement();//判断是否在编辑器内 if(p.tagName=="INPUT"||p==document.body)ieRange=false; } } } function insert(){ if(txt.value==''){alert('请输入内容!'); txt.focus();return false;} if(ieRange){ ieRange.pasteHTML(txt.value); txt.value=''; ieRange.select();ieRange=false;//清空下range对象 } else{//焦点不在html编辑器内容时 win.focus(); if(isIE)doc.body.innerHTML+=txt.value;//IE插入在最后 else{//Firefox var sel=win.getSelection(),rng=sel.getRangeAt(0),frg=rng.createContextualFragment(txt.value); rng.insertNode(frg); } } } </script> </body> </html>
加支付宝好友偷能量挖...
原创文章,转载请注明出处:HTML编辑器失去焦点后在原来光标位置插入信息/图片