1

contenteditable div と、単純なスパンを追加するボタンがあります。

<button id="insert-span">Insert</button>
<div id="edit-box" contenteditable="true"></div>
<script>
    $('#insert-span').on('click', function() {
        document.execCommand('insertHTML', null, '<span class="inserted">Hi</span>');
    });
</script>

ボタンをクリックすると、スパンがdivに正しく追加されますが、さらにテキストを入力すると、挿入されたスパン内にあるため、このようになります

<div id="edit-box" contenteditable="true">
    <span class="inserted">Hi and then all the other text I enter</span>
</div>

このような結果になるように、スパンタグの外側にテキストの入力を開始する方法はありますか

<div id="edit-box" contenteditable="true">
    <span class="inserted">Hi</span> and then all the other text I enter
</div>
4

2 に答える 2

1

なぜそれをするのかわかりませんが、これでうまくいくはずです:

var text = document.createTextNode('your text after the span');
edit_box.appendChild(text);
于 2013-02-05T18:51:14.053 に答える
0

すでに jQuery を使用しているので、ここで jquery prepend メソッドの使用を検討してみませんか?

$('#insert-span').on('click', function() {     
    $('#edit-box').prepend('<span class="inserted">Hi</span> and then all the other text I enter');
});
于 2013-02-05T18:44:29.023 に答える