Range,这是个很容易被人忽略的东西,在开发富文本编辑器时会经常用到。使用iframe设计模式或div的 contenteditable=“true” 。
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <head> <title></title> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> </head> <body> <div id="div" contenteditable="true" style="width:300px;height:100px;border:1px solid #000"><br /></div> <input type="button" value="插入" οnclick="test('测试一下')" οnfοcus="this.blur()" /> <script type="text/javascript"> function test(str){ if(!document.all){ alert("仅在IE中可以查看"); return; } document.getElementById('div').focus(); var selection= window.getSelection ? window.getSelection() : document.selection; var range= selection.createRange ? selection.createRange() : selection.getRangeAt(0); range.pasteHTML(str); range.collapse(false); range.select(); } </script> </body> </html> 提示:您可以先修改部分代码再运行
<html> <head> <title></title> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> </head> <body> <div id="div" contenteditable="true" style="width:300px;height:100px;border:1px solid #000"><br /></div> <input type="button" value="插入" οnclick="test('测试一下')" οnfοcus="this.blur()" /> <script type="text/javascript"> function test(str){ var selection= window.getSelection ? window.getSelection() : document.selection; var range= selection.createRange ? selection.createRange() : selection.getRangeAt(0); if (!window.getSelection){alert("请在支持w3c标准的浏览器查看")} else{ document.getElementById('div').focus(); range.collapse(false); var hasR = range.createContextualFragment(str); var hasR_lastChild = hasR.lastChild; while (hasR_lastChild && hasR_lastChild.nodeName.toLowerCase() == "br" && hasR_lastChild.previousSibling && hasR_lastChild.previousSibling.nodeName.toLowerCase() == "br") { var e = hasR_lastChild; hasR_lastChild = hasR_lastChild.previousSibling; hasR.removeChild(e) } range.insertNode(hasR); if (hasR_lastChild) { range.setEndAfter(hasR_lastChild); range.setStartAfter(hasR_lastChild) } selection.removeAllRanges(); selection.addRange(range) } } </script> </body> </html>
提示:您可以先修改部分代码再运行 |
JavaScript Range用来开发类似于百度贴吧和webqq的编辑器
最新推荐文章于 2019-03-30 23:00:09 发布