admin管理员组

文章数量:1327991

I want to insert a line break and set the caret position in the new line.

I have this

<!-- editable -->
<div>
    hello
</div>

Then I add a new line

document.execCommand("insertHtml", false, "world" + "<br> ");

But the caret is not moved after the <br>, so when I type the text doesn't go to the new line.

How can I set the caret position in the new line so when I type it goes bellow?

Actual result:

helloworld<typedtext>

Expected result:

helloworld
<typedtext>

Example on jsFiddle

Tested on Chrome 15

I want to insert a line break and set the caret position in the new line.

I have this

<!-- editable -->
<div>
    hello
</div>

Then I add a new line

document.execCommand("insertHtml", false, "world" + "<br> ");

But the caret is not moved after the <br>, so when I type the text doesn't go to the new line.

How can I set the caret position in the new line so when I type it goes bellow?

Actual result:

helloworld<typedtext>

Expected result:

helloworld
<typedtext>

Example on jsFiddle

Tested on Chrome 15

Share Improve this question edited Aug 14, 2011 at 20:44 BrunoLM asked Aug 14, 2011 at 15:54 BrunoLMBrunoLM 100k86 gold badges309 silver badges461 bronze badges 2
  • that's working for me but no in ie9, jsfiddle/BhZzu – Eric Fortis Commented Aug 14, 2011 at 16:08
  • It works for me on Chrome Canary. – pimvdb Commented Aug 14, 2011 at 16:43
Add a ment  | 

2 Answers 2

Reset to default 4

just add a line break and it will move it in chrome so some thing like this

document.execCommand("insertHtml", false, "world");
document.execCommand('insertParagraph',false); 

Question was asked a while ago but hope it helps someone anyway

document.execCommand('insertText', true, 'hi\\r\\nworld')

本文标签: javascriptHow to use execCommand to set a new lineStack Overflow