JavaScript Range用来开发类似于百度贴吧和webqq的编辑器
? </head>
? <body>
? ? ? <div id="div" contenteditable="true" style="width:300px;height:100px;border:1px solid #000"><br /></div>
? ? ? <input type="button" value="插入" onclick="test('测试一下')" onfocus="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>? ?? ?
? ? </head>
? ? <body>
? ? ? ? <div id="div" contenteditable="true" style="width:300px;height:100px;border:1px solid #000"><br /></div>
? ? ? ? <input type="button" value="插入" onclick="test('测试一下')" onfocus="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>
?
?
?
?提示:您可以先修改部分代码再运行
? ?? ?? ?? ?? ?? ? W3C标准的这个也下周再做注释
要下班了,下周继续吧。 会有编辑器要重新定义回车、获取选中的内容以替换、粘贴html图片时候过滤、保存range等。