Preserve at least one P element inside contenteditable

…衆ロ難τιáo~ 提交于 2020-01-17 06:05:00

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!