使用 jQuery/JavaScript 复制到剪贴板文本框值



我有一个文本框和按钮,看起来像这样:

<div class="col-xs-11" style="padding:20px 0 ">
<input type="text" class="form-control txtKeywords" id="txtKeyw" style="margin-bottom:10px; height:45px;" maxlength="80" placeholder="Click on keywords to combine your title">
<button type="submit" class="btn btn-space btn-success btn-shade4 btn-lg copyToClipboard">
<i class="icon icon-left s7-mouse"></i> Copy to Clipboard
/button>

当用户单击按钮复制到剪贴板时,我想将文本框的内容复制到剪贴板中,如下所示:

$(document).on("click", ".copyToClipboard", function () {
copyToClipboard("txtKeyw");
successMessage();
});

其中copyToClipboard函数的定义是:

function copyToClipboard(element) {
var $temp = $("<input>");
$("body").append($temp);
$temp.val($(element).text()).select();
document.execCommand("copy");
$temp.remove();
}

但是当我这样做时,什么也没发生 - 没有值从文本框复制到剪贴板......我在这里做错了什么?

更多信息:

  • 这在Chrome 59 64位和Firefox 54 32位中都会发生。
  • successMessage()被调用并显示在浏览器中。
  • 在元素的 ID 前面添加#并不能解决问题。

第 1 步:像这样更改copyToClipboard(element)

function copyToClipboard(text) {
var textArea = document.createElement( "textarea" );
textArea.value = text;
document.body.appendChild( textArea );       
textArea.select();
try {
var successful = document.execCommand( 'copy' );
var msg = successful ? 'successful' : 'unsuccessful';
console.log('Copying text command was ' + msg);
} catch (err) {
console.log('Oops, unable to copy',err);
}    
document.body.removeChild( textArea );
}

第2步:给你的按钮一个id,然后像这样添加一个事件侦听器:

$( '#btnCopyToClipboard' ).click( function()
{
var clipboardText = "";
clipboardText = $( '#txtKeyw' ).val(); 
copyToClipboard( clipboardText );
alert( "Copied to Clipboard" );
});

试试这个。这是正确的方法。

第 1 步:

function copyToClipboard(text) {
var textArea = document.createElement( "textarea" );
textArea.value = text;
document.body.appendChild( textArea );
textArea.select();
try {
var successful = document.execCommand( 'copy' );
var msg = successful ? 'successful' : 'unsuccessful';
console.log('Copying text command was ' + msg);
} catch (err) {
console.log('Oops, unable to copy');
}
document.body.removeChild( textArea );
}

第 2 步:

$( '#btnCopyToClipboard' ).click( function()
{
var clipboardText = "";
clipboardText = $( '#txtKeyw' ).val();
copyToClipboard( clipboardText );
alert( "Copied to Clipboard" );
});

copyToClipboard()获取一个元素作为参数。txtKeyw是 id,您必须#放在它前面。

我相信document.execCommand('copy'(现在已经不推荐使用,在Edge v 113.0和Opera v 98.0上进行了测试

请改用这个:

function copyToClipboard() {
var txtField = document.getElementById('txt-field');
txtField.select();
navigator.clipboard.writeText(txtField.value);
alert('Copied to clipboard!');
}

最新更新