[英]text cursor not updating in contenteditable span within div element
The text cursor position was not updating while editing a <span>
element within a <div>
element so I decided to post this Q & A just in case anyone else ran into the same problem. 在编辑
<div>
元素中的<span>
元素时,文本光标的位置没有更新,因此我决定发布此问与答,以防其他人遇到相同的问题。 Why is the text cursor not updating it's position? 为什么文本光标不更新其位置? It updates fine when it is not wrapped in a
<div>
element. 当它没有包装在
<div>
元素中时,它会更新良好。 Take a look at the sample code below. 看下面的示例代码。 The text cursor seems to "freeze" at position 1 (or after the first letter in the
span
). 文本光标似乎在位置1(或
span
的第一个字母之后)“冻结”。
Notes: 笔记:
<span>
element has contenteditable="true"
. <span>
元素具有contenteditable="true"
。 contenteditable
is not set on the <div>
element. <div>
元素上设置contenteditable
。 $('.editableSpan').on('click keydown', function(e) { if ($(this).css('background-color') !== 'rgba(0, 0, 0, 0)') { $(this).css('background-color', ''); $(this).text(''); } });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div>This is a div with <span class="editableSpan" contenteditable="true" style="background-color: rgb(250, 197, 28);">an editable span</span>.</div> <span class="editableSpan" contenteditable="true" style="background-color: rgb(250, 197, 28);">This is an editable span</span>
A simple fix to this issue is setting display: inline-block;
解决此问题的一个简单方法是设置
display: inline-block;
to the <span>
element. 到
<span>
元素。 However, I am not sure as to why this works. 但是,我不确定这为什么起作用。 Please feel free to add to this Q & A to describe why this works.
请随时在此问答中添加说明原因。 Thanks.
谢谢。
$('.editableSpan').on('click keydown', function(e) { if ($(this).css('background-color') !== 'rgba(0, 0, 0, 0)') { $(this).css('background-color', ''); $(this).text(''); } });
.editableSpan { display: inline-block; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div>This is a div with <span class="editableSpan" contenteditable="true" style="background-color: rgb(250, 197, 28);">an editable span</span>.</div> <span class="editableSpan" contenteditable="true" style="background-color: rgb(250, 197, 28);">This is an editable span</span>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.