The only way what I found till now is document.queryCommandSupported('insertText')
, though it seems incorrect, for example this code not works in firefox, but above command returns true
txt = "aaaaaaaaaaaa"; $(document).ready(function() { console.log( document.queryCommandSupported('insertText') ); $("#myinp").focus(); document.execCommand("insertText", false, txt); });
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <textarea id="myinp" ></textarea>
So, what is correct way for this?
document.execCommand("insertText", false, txt)
returns true
/ false
, so you can just use:
if (document.execCommand("insertText", false, txt)) {
// it worked
} else {
// it didn't work
}
If you're looking for a cross-browser way to insert text, try text-field-edit . If you need IE8+ support, try the insert-text-at-cursor package. Both of them already run this check and have a fallback.
The following demo will insert the text from the <textarea>
at the bottom to the contenteditable
<fieldset>
at the top. .execCommand()
needs to be within an event handler/callback function and it edits elements with the [contenteditable]
attribute -- that could be any tag except form controls such as <textarea>
, or <input>
. The demo has .execCommand()
within a mouseup
event delegation.
Instructions
Type some text in the <textarea>
at the bottom..
Click anywhere or select any text within the <fieldset>
.
The text in the <textarea>
will be inserted where the cursor is or where the text was selected within the <fieldset>
$('.editor').on('mouseup', function() { var txt = $('.insert').val(); document.execCommand("insertText", false, txt); });
<fieldset class="editor" contenteditable='true'></fieldset> <textarea class='insert'style='min-width:98%'></textarea> <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
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.