I have a div with contenteditable set and I am capturing keypress using jquery to call preventDefault() when the enter key is pressed. Similar to this question which inserts text at the cursor, I would like to directly insert html, for brevity we'll say its a br tag. Using the answer to the question above actually works in IE as it uses the range.pasteHTML method, but in other browsers the br tag would appear as plain text and not html. How could I modify the answer to insert html and not text ?
相关问题
- Is there a limit to how many levels you can nest i
- How to toggle on Order in ReactJS
- How to fix IE ClearType + jQuery opacity problem i
- void before promise syntax
- jQuery add and remove delay
In most browsers, you can use the
insertNode()
method of the Range you obtain from the selection. In IE < 9 you can usepasteHTML()
, as you mentioned. Below is a function to do this in all major browsers. If content is already selected, it is replaced, so this is effectively a paste operation. Also, I added code to place the caret after the end of the inserted content.jsFiddle: http://jsfiddle.net/jwvha/1/
Code:
UPDATE 21 AUGUST 2013
As requested in the comments, here is an updated example with an extra parameter that specifies whether or not to select the inserted content.
Demo: http://jsfiddle.net/timdown/jwvha/527/
Code: