将文本区域的文本复制到剪贴板HTML / JavaScript

3

嘿,我知道有很多教程,但似乎都对我没有用。

我有这个:

<textarea name="forum_link" type="text" style="width:630px; height:90px;">
[URL=http://www.site.net/video/<?=$_GET['id']?>/<?=$_GET['tag']?>]<?=$video->title?>[/URL]

[URL=http://www.site.net/video/<?=$_GET['id']?>/<?=$_GET['tag']?>][IMG]<?=$video->thumbnailURL?>[/IMG][/URL]
</textarea>

现在我需要的是一个简单的按钮,当点击它时,将文本框中的文本复制到用户的剪贴板中。
有任何帮助都会很棒 :)
谢谢
7个回答

13
<textarea id="html" name="html">Some text</textarea>
<input type="button" value="Refresh" onclick="copy_to_clipboard('html');">

<script>
function copy_to_clipboard(id)
{
    document.getElementById(id).select();
    document.execCommand('copy');
}
</script>

1

这个解决方案纯粹基于Javascript。我不知道它是否兼容其他浏览器。在Chrome上可以运行,我正在添加代码片段。

//all text written(inside text area), is copied and shown inside the div with class "mas"
//you can't see it, as it is hidden(opacity is 0)

$('#content:not(.focus)').keyup(function(){     
        
        
    var value = $(this).val();
    var contentAttr = $(this).attr('name');
    
    $('.'+contentAttr+'').html(value.replace(/\r?\n/g,'<br/>'));
    
})

//below code can copy text inside a div. div id should be identical with button oclick id  

copyToClipboard = function (element) {
    var $temp = $("<input />");
    $("body").append($temp);
    $temp.val($(element).text()).select();

    var result = false;
    try {
        result = document.execCommand("copy");
    } catch (err) {
        console.log("Copy error: " + err);
    }

    $temp.remove();
    return result;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<textarea name="mas" rows="6" id="content"></textarea>
<p>&nbsp;</p>
<div id="p1" class="mas" style="top:0px;position:absolute;opacity:0;" ></div>

<button onclick="copyToClipboard('#p1')">Copy P1</button>

请查看此Jsfiddle以获取更多详细信息。

1

评论表明这仅适用于IE浏览器。 - Quentin

1

很遗憾,这方面没有一种全能的解决方案。除了IE浏览器之外的其他浏览器都不允许复制到剪贴板。我最近找到了一个好的解决方案,它使用Flash(适用于除IE之外的所有浏览器)和JavaScript(适用于IE)将文本复制到剪贴板。有关详细信息,请参见zeroclipboard


这个已经过时了,看下面MeKoo Solution的回答获取更加实时的答案。 - RobPethi

0
浏览器兼容性在使用任何脚本时都很糟糕。JavaScript故意不允许与操作系统进行这种级别的功能交互。虽然可以创建一个签名脚本,但是这需要更多的工作量,而且几乎没有什么价值。大多数人都知道如何复制和粘贴...

0

很遗憾,JavaScript没有一种通用的方法。目前,使用Flash和JavaScript是最通用的方式。 看看LMCButton - 一个小型动画Flash按钮(4 kb),用于“复制到剪贴板”。

使用JavaScript的示例:

获取按钮的HTML代码:function lmc_get_button(cliptext, idLMC)

更新按钮中的文本:function lmc_set_text(idLMC, text)


0

现代解决方案

document.execCommand('copy')现在已经弃用

相反,我们现在有了Clipboard API

您可以使用writeText()属性来实现此目的:

$('button').on('click', () => {
  navigator.clipboard.writeText($('textarea').val()).then(
    () => {
      console.log('clipboard successfully set');
    },
    () => {
      console.error('clipboard write failed');
    }
  );
});

或者简单地说:

$('button').on('click', () => {
  navigator.clipboard.writeText($('textarea').val());
});

奖励:此方法适用于禁用的文本区域,并且可以跨浏览器使用。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接