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. Why is the text cursor not updating it's position? It updates fine when it is not wrapped in a <div>
element. 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
).
Notes:
<span>
element has contenteditable="true"
. contenteditable
is not set on the <div>
element. $('.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;
to the <span>
element. 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>
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.