简体   繁体   中英

How to I prevent deletion of contenteditable span?

I'm trying to use a contenteditable span . But if, as the user, I delete all the text within the span, the span disappears and is no longer editable (still in the DOM though). How do I prevent this?

I'm seeing this problem in both Chrome and FF.

Here's what I've tried:

 <div class="subgroup" contenteditable="false" style="border: 1px solid red;"> <span class="header editable" contenteditable="true">initial contents</span> </div>

I put contenteditable="false" on the parent element based on this answer from 2015 , but the result is the same whether or not that attribute is present on the parent.

Of course, I could have JS intercept keypresses to prevent the user from completely clearing the contents, but that's a bad UX. I'd much prefer a pure HTML solution in any event.

In writing up this question, I discovered a solution. For others who might need it: put a border on the span .

But there, as suggested by @G-Cyrillus, a better solution is to add padding to the span when the node is empty:

 <style>.subgroup span:empty { padding-right:1em;} </style> <div class="subgroup" contenteditable="false" style="border: 1px solid red;"> <span class="header editable" contenteditable="true">initial contents</span> </div>

Anyone have a better solution?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM