插入div在contenteditable

时间:2015-06-15 08:26:26

标签: javascript contenteditable

我尝试将div文字插入contenteditable并在添加div后选择div标记之间的文字:

div.innerHTML +='<div id="id">selecttext</div>'

但这不会选择selecttext

<html>
    <head></head>
    <body>
        <div id="contenteditable" contenteditable></div>
        <script>
            var contenteditable = document.getElementById("contenteditable");

            contenteditable.onkeyup = function (e) {
                contenteditable.innerHTML += '<div>Start here</div>';
            }
        </script>
    </body>
</html>

1 个答案:

答案 0 :(得分:0)

您的问题分为三个部分:

  
      
  1. 将带有文字的div插入contenteditable
  2.   
contenteditable.innerHTML += '<div id="startHere">Start Here</div>';
  
      
  1. 查找startHere div
  2.   
function findStartHereDiv(contenteditable) {
    var childNodes = contenteditable.childNodes;
    for(var i = 0; i < childNodes.length; i++) {
        if(childNodes[i].id == 'startHere') {
            return childNodes[i];
            break;
        }
    }
   return null; 
}
  
      
  1. 选择startHere div的文字:
  2.   
function selectText(element) {
    var doc = document
        , text = doc.getElementById(element)
        , range, selection
    ;    
    if (doc.body.createTextRange) {
        range = document.body.createTextRange();
        range.moveToElementText(text);
        range.select();
    } else if (window.getSelection) {
        selection = window.getSelection();        
        range = document.createRange();
        range.selectNodeContents(text);
        selection.removeAllRanges();
        selection.addRange(range);
    }
}

这是你需要的吗?

DEMO