[英]Check if browser supports document.execCommand insertText
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
到目前为止我发现的唯一方法是
document.queryCommandSupported('insertText')
,虽然它看起来不正确,例如这段代码在 firefox 中不起作用,但上面的命令返回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: document.execCommand("insertText", false, txt)
返回true
/ false
,因此您可以使用:
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 .如果您正在寻找一种跨浏览器的方式来插入文本,请尝试text-field-edit 。 If you need IE8+ support, try the insert-text-at-cursor package.
如果您需要 IE8+ 支持,请尝试insert-text-at-cursor包。 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.下面的演示会将底部的
<textarea>
中的文本插入到顶部的contenteditable
<fieldset>
中。 .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>
. .execCommand()
需要在事件处理程序/回调函数中,并且它编辑具有[contenteditable]
属性的元素——它可以是除了表单控件之外的任何标记,例如<textarea>
或<input>
。 The demo has .execCommand()
within a mouseup
event delegation.该演示在
mouseup
事件委托中有.execCommand()
。
Instructions指示
Type some text in the <textarea>
at the bottom..在底部的
<textarea>
中键入一些文本..
Click anywhere or select any text within the <fieldset>
.单击任意位置或选择
<fieldset>
中的任何文本。
The text in the <textarea>
will be inserted where the cursor is or where the text was selected within the <fieldset>
<textarea>
中的文本将插入光标所在的位置或<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>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.