JavaScript满足

时间:2013-05-15 20:46:25

标签: javascript contenteditable

我正在创建一个HTML富文本编辑器,我想在div上使用contenteditable属性。我在一个名为编辑器的div中有一个div列表。当用户点击进入时,我阻止默认操作。然后我在当前div之后插入一个新的div。唯一的问题是我不能专注于新的div。有谁知道怎么做?

HTML

<body>
        <div id="editor" contenteditable="true">
            <div id="1" contenteditable="ture" class="line" style="height: 20px; background-color: #a0f;"></div>
            <div contenteditable="ture" class="line" style="height: 20px; background-color: #abf;"></div>
            <div contenteditable="ture" class="line" style="height: 20px; background-color: #a9f;"></div>
            <div contenteditable="ture" class="line" style="height: 20px; background-color: #aff;"></div>
            <div contenteditable="ture" class="line" style="height: 20px; background-color: #aaf;"></div>
        </div>
    </body>

<body> <div id="editor" contenteditable="true"> <div id="1" contenteditable="ture" class="line" style="height: 20px; background-color: #a0f;"></div> <div contenteditable="ture" class="line" style="height: 20px; background-color: #abf;"></div> <div contenteditable="ture" class="line" style="height: 20px; background-color: #a9f;"></div> <div contenteditable="ture" class="line" style="height: 20px; background-color: #aff;"></div> <div contenteditable="ture" class="line" style="height: 20px; background-color: #aaf;"></div> </div> </body>

JavaScript

 $(function(){

        var thisLine;

        $("#editor").bind("keydown", function(event){
            if(event.keyCode == 13){
                event.preventDefault(); 
                var newLine = $("<div tabindex=\"-1\" contenteditable=\"ture\" id=\"2\"class=\"line\" style=\"height: 20px; background-color: #aff;\"></div>");
                        newLine.insertAfter(thisLine);
                        $("#2").focus();
                    }
                })

                $(".line").bind("click", function(){
                    thisLine = $(this);
                })

            });

2 个答案:

答案 0 :(得分:0)

这应该有效:

newLine.insertAfter(thisLine).focus();

演示:http://jsfiddle.net/tymeJV/7xEXt/

答案 1 :(得分:0)

获取选择,并为其添加新的折叠范围。请参阅示例中的moveCaretToStartOf方法

&#13;
&#13;
function moveCaretToStartOf(element) {
  var selection = document.getSelection();
  selection.removeAllRanges();
  var range = document.createRange();
  range.setStart(element, 0);
  selection.addRange(range)
}

document.querySelector('div').focus();
window.setTimeout(function () {
	moveCaretToStartOf(document.querySelectorAll('p')[1])
}, 1000);
&#13;
<blockquote>
  Cursor will be placed into the second paragraph after 1 second
</blockquote>
<div contenteditable="true">
  <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Vel laboriosam nobis nam tempore sint adipisci, ullam perspiciatis placeat aliquid dolorem. Aliquid nisi, dicta sunt dolor qui voluptatem perferendis veniam ad!</p>
  <p><br></p>
</div>
&#13;
&#13;
&#13;