将文本复制到客户端的剪贴板涉及几个步骤:
要使用 jQuery 完成此操作,请按照以下步骤操作:
<code class="html"><script src="https://code.jquery.com/jquery-3.6.0.min.js"></script></code>
<code class="html"><textarea id="my-textarea"></textarea> <script> $( "#my-textarea" ).on( "click", function() { // Get the selected text var selectedText = $(this).val(); // Clipboard API is not supported in all browsers if (!navigator.clipboard) { console.error("Clipboard API not supported"); return; } // Set the selected text to the clipboard navigator.clipboard.writeText(selectedText).then(() => { // Success alert("Text copied to clipboard!"); }, () => { // Error alert("Failed to copy text to clipboard"); }); }); </script></code>
此方法使用大多数现代浏览器都支持的剪贴板 API。如果您的目标受众包括较旧的浏览器,请考虑使用后备方法,例如使用 ZeroClipboard 或 Flash,如提供的答案中所述。
以上是如何使用 jQuery 将文本复制到客户端的剪贴板?的详细内容。更多信息请关注PHP中文网其他相关文章!