问题
I have a contenteditable with a <p>
element inside it like the following
<div class="editable" contenteditable="true">
<p>
dummy content here !!!!!
</p>
</div>
When I click backspace on the keybord until it remove all the text, if I click the backspace again it removes also the <p>
element ! In my case I would like to keep at least one <p>
element there
$(document).on('keydown', '[contenteditable=true]', function(e){
var contenteditable = $(this)
if(e.keyCode == 8){ // if backspace
var p = contenteditable.find('p');
var pLength = p.length;
if(pLength == 1){ // if only one <p> exists inside contenteditable
var pHtml = p.html();
// if only <br> is still inside <p> then prevent
// the backspace to delete the <p>
if( pHtml == "<br>" || pHtml == ""){
e.preventDefault()
}
}
}
});
But it doesn't work ! also I want to prevent the deletion of <p>
if the user select the whole text at once using Ctrl+A or the mouse and hits the Backspace key.
I am also not sure if my method is the best way to go, but I am open to all suggestions ! thanks
UPDATE :
I've found another way to do it but still not complete :
$(document).on('keyup', '[contenteditable=true]', function(e){
var contenteditable = $(this);
if( e.keyCode == 8 ) {
if(contenteditable.find('p').length == 0){
contenteditable.html('<p><br></p>');
}
}
});
on Backspace keydown I check if no P element exists inside the contenteditable, if no element found I add one with <br>
inside, but still need to set the caret before the br
来源:https://stackoverflow.com/questions/37365253/preserve-at-least-one-p-element-inside-contenteditable