Make part of contentEditable unable to delete

我们两清 提交于 2021-02-04 16:14:07

问题


I have a contentEditable Div, and I'd like to be able to "protect" portions of it from deletions.

For instance, I have this contentEditable DIV that has an img tag in it I'd like to never get deleted. But I need to maintain the text flow around the image as the user types.

http://jsfiddle.net/uk6DA/16/

Is there any way, using formatting of inner DIV's, or any other way. I have experimented with key events but so far only have had sporadic results.


回答1:


Look at the Demo

http://jsfiddle.net/uk6DA/21/

you need to apply the contenteditable for paragraphs only.

<div class="container" id="typer" style="border:1px solid gray; height:300px; width:520px; padding:4px; text-align:justify; text-justify:distribute-all-lines;">


        <img style="border:1px solid #cccccc; float: left; margin: 3px;" src="http://ts1.mm.bing.net/th?id=I4951402157179616&pid=1.7&w=139&h=136&c=7&rs=1" /><p>  
    If I Select All and press Delete, or press Backspace enough times, I can delete the troll.  Is there any way to make it impossible to delete the troll?<br/><br/>
    Curabitur nec metus arcu. Sed aliquam felis at leo luctus facilisis. Maecenas tortor urna, dignissim id imperdiet nec, vulputate a nisl. Morbi turpis augue, malesuada et viverra blandit, ultrices at eros. Ut id urna vitae odio iaculis ullamcorper. Proin tortor est, adipiscing id rutrum vitae, blandit ac purus. Maecenas eu turpis lectus, quis elementum nisi. Nullam lobortis, lectus eu ornare iaculis, felis lacus condimentum sapien, id laoreet velit neque at metus. Etiam scelerisque pulvinar dignissim. Proin rhoncus iaculis dolor, vel tincidunt velit feugiat quis. Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Sed tellus quam, gravida vel posuere at, elementum eu 


               <p> </div>​

javascript

$("#typer").click(function(){
$(this).children('p').attr('contentEditable','true');
});​



回答2:


Yes you can do it easy way. Just add attribute to your image contenteditable="false" and element with this attribute wont be affected with edit commands.

so basically your img tag should look like this:

 <img contenteditable="false" style="border:1px solid #cccccc; float: left; margin: 3px;" src="http://ts1.mm.bing.net/th?id=I4951402157179616&pid=1.7&w=139&h=136&c=7&rs=1" />  

and fiddle to show it http://jsfiddle.net/uk6DA/17/



来源:https://stackoverflow.com/questions/12014713/make-part-of-contenteditable-unable-to-delete

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