Force IE contentEditable element to create line br

2019-01-13 20:30发布

On Internet Explorer, a contentEditable DIV creates a new paragraph (<p></p>) each time you press Enter whereas Firefox creates a <br/> tag.

As discussed here, it is possible to use JavaScript to intercept the Enter keyPress and use range.pasteHTML to create a <br/> instead. But doing this breaks the Undo menu; once you hit Enter, you can no longer Undo past that point.

How can I force the contentEditable element to create single line breaks on Enter without breaking Undo?

7条回答
做自己的国王
2楼-- · 2019-01-13 21:14

It may be impossible to get this right. However, it is possible to make the <p> tags look like single line breaks, by removing the built-in margin around paragraph tags, using CSS:

p { margin: 0; }

There is a drawback to this approach: if the user needs to copy/paste text in the contentEditable element, the text may appear to be single-spaced inside the element but double-spaced outside the element.

Worse, in at least some cases, IE will automatically detect double-line breaks during paste, replacing them with <p> tags; this will mess up the formatting of the pasted text.

查看更多
登录 后发表回答