You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

2 vuotta sitten
1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  1. <!DOCTYPE html>
  2. <html lang="en">
  3. <head>
  4. <meta charset="UTF-8">
  5. <title>contenteditable</title>
  6. <style>
  7. #insert{
  8. width: 90px;
  9. height: 30px;
  10. border: 1px solid #ccc;
  11. background-color: #fff;
  12. margin: 10px;
  13. }
  14. #editor{
  15. padding: 10px;
  16. overflow-y: auto;
  17. min-height:200px;
  18. border:1px solid #f33;
  19. outline: 0;
  20. }
  21. #editor h4{
  22. margin: 10px 0;
  23. }
  24. </style>
  25. </head>
  26. <body>
  27. <button type="button" id='insert'>插入标题</button>
  28. <div contentEditable="true" id="editor">
  29. <h3>副标题</h3>
  30. <p>文本</p>
  31. </div>
  32. </body>
  33. <script>
  34. document.getElementById('insert').onclick=function(){
  35. var content = prompt('请输入内容');
  36. document.getElementById('editor').focus();
  37. if(!!content){
  38. insertHtml('<span>'+content+'</span>');
  39. }
  40. }
  41. document.getElementById('editor').onpaste=function(event){
  42. var e = event || window.event
  43. e.preventDefault();
  44. var text = (e.originalEvent || e).clipboardData.getData('text/plain') || prompt('在这里输入文本');
  45. document.execCommand("insertText", false, text);
  46. };
  47. function insertHtml(html) {
  48. var sel = window.getSelection(),
  49. range;
  50. if (sel.getRangeAt && sel.rangeCount) {
  51. range = sel.getRangeAt(0);
  52. range.deleteContents();
  53. var el = document.createElement("span");
  54. el.innerHTML = html;
  55. var frag = document.createDocumentFragment(), node, lastNode;
  56. while ( (node = el.firstChild) ) {
  57. lastNode = frag.appendChild(node);
  58. }
  59. range.insertNode(frag);
  60. if (lastNode) {
  61. range = range.cloneRange();
  62. range.setStartAfter(lastNode);
  63. range.collapse(true);
  64. sel.removeAllRanges();
  65. sel.addRange(range);
  66. }
  67. }
  68. }
  69. </script>
  70. </html>