1

HTML リッチ テキスト エディターを作成しており、div で contenteditable 属性を使用したいと考えています。エディターと呼ばれる div 内に div のリストがあります。ユーザーがEnterキーを押すと、デフォルトのアクションが防止されます。次に、現在の 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>

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);
                })

            });

4

2 に答える 2

0

選択範囲を取得し、新しい折りたたまれた範囲をそれに追加します。moveCaretToStartOf例のメソッドを参照してください

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);
<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>

于 2016-02-03T20:24:53.283 に答える