|
1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677 |
- <!DOCTYPE html>
- <html lang="en">
- <head>
- <meta charset="UTF-8">
- <title>contenteditable</title>
- <style>
- #insert{
- width: 90px;
- height: 30px;
- border: 1px solid #ccc;
- background-color: #fff;
- margin: 10px;
- }
- #editor{
- padding: 10px;
- overflow-y: auto;
- min-height:200px;
- border:1px solid #f33;
- outline: 0;
- }
- #editor h4{
- margin: 10px 0;
- }
- </style>
- </head>
- <body>
-
- <button type="button" id='insert'>插入标题</button>
- <div contentEditable="true" id="editor">
- <h3>副标题</h3>
- <p>文本</p>
- </div>
-
- </body>
- <script>
-
- document.getElementById('insert').onclick=function(){
- var content = prompt('请输入内容');
- document.getElementById('editor').focus();
- if(!!content){
- insertHtml('<span>'+content+'</span>');
- }
- }
-
- document.getElementById('editor').onpaste=function(event){
- var e = event || window.event
- e.preventDefault();
- var text = (e.originalEvent || e).clipboardData.getData('text/plain') || prompt('在这里输入文本');
-
- document.execCommand("insertText", false, text);
- };
-
- function insertHtml(html) {
- var sel = window.getSelection(),
- range;
-
- if (sel.getRangeAt && sel.rangeCount) {
- range = sel.getRangeAt(0);
- range.deleteContents();
- var el = document.createElement("span");
- el.innerHTML = html;
- var frag = document.createDocumentFragment(), node, lastNode;
- while ( (node = el.firstChild) ) {
- lastNode = frag.appendChild(node);
- }
- range.insertNode(frag);
- if (lastNode) {
- range = range.cloneRange();
- range.setStartAfter(lastNode);
- range.collapse(true);
- sel.removeAllRanges();
- sel.addRange(range);
- }
- }
- }
- </script>
- </html>
|