[英]How to prevent remove inside span using contenteditable?
I have a editor using HTML 5 tag contenteditable
, there i'm using span
inside contenteditable
, when i remove all text then span also removed but i want span should not be removed, how to prevent it?我有一个使用 HTML 5 标签contenteditable
的编辑器,我在contenteditable
使用了span
,当我删除所有文本时,span 也被删除了,但我希望 span 不应该被删除,如何防止它?
My Code:--我的代码:--
$('#editor').keyup(function(){ $('#spanText').text($(this).find('span').text()); });
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <div contenteditable="true" id="editor"><span>This is my text</span></div> <br><br><hr> <div id="spanText"></div>
I think there is no straightforward way to achieve that.我认为没有直接的方法可以实现这一目标。
You can check the text length of the element to restore the element back.您可以检查元素的文本长度以将元素恢复回来。
Demo:演示:
$('#editor').keyup(function(){ if(!$(this).text().length){ $(this).html('<span> </span>'); } $('#spanText').text($(this).find('span').text().trim()); });
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <div> <div contenteditable="true" id="editor"><span>This is my text</span></div> </div> <hr> <div id="spanText"></div>
Move the contenteditable property to the span将 contenteditable 属性移动到 span
<div>
<span contenteditable="true" id="editor">This is my text</span>
</div>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.