使用 PHP 和 JavaScript 将文本复制到剪贴板?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/50729670/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Copy text to the clipboard with PHP and JavaScript?
提问by Bear. Teddy Bear.
I want to include a button on an existing webpage that will copy text to the Windows clipboard.
我想在现有网页上添加一个按钮,将文本复制到 Windows 剪贴板。
The webpage and the PHP in it already works well to create and display text like this:
网页和其中的 PHP 已经可以很好地创建和显示这样的文本:
Output on webpage:
网页输出:
'Abby Normal' <[email protected]>, 'Brad Majors' <[email protected]>, 'Frank N. Furter' <[email protected]>
So now I want to add a Javascript function and an html button that calls that function to copy that output to the Windows clipboard.
所以现在我想添加一个 Javascript 函数和一个 html 按钮,调用该函数将该输出复制到 Windows 剪贴板。
Problem: nothing is copied when the button is pressed. What am I doing wrong? Thank you in advance.
问题:按下按钮时不会复制任何内容。我究竟做错了什么?先感谢您。
<?PHP
session_start();
include('include/_initsess.php');
include('include/_setdb.php');
if(!isset($_SESSION['userlist'])) exit;
$users = $_SESSION['userlist'];
$emails = '';
$qry = "SELECT FIRST,LAST,EMAIL FROM users WHERE PKEY IN ($users)";
$result = mysql_query($qry);
$numrows = mysql_num_rows($result);
for ($m=0; $m<$numrows; $m++) {
$row = mysql_fetch_array($result);
list($fn,$ln,$em) = $row;
$emails .= ($m==0) ? "'".$fn." ".$ln."' <".$em.">" : (", '".$fn." ".$ln."' <".$em.">");
} // end for
?>
<html>
<head>
</head>
<body>
<span class=mono id="theList" value="<?php echo $emails; ?>">
<?PHP echo($emails); ?>
</span>
<script>
function copyToClipboardWithJavascript() {
/* Get the text field */
var copyText = document.getElementById("theList");
/* Select the text field */
copyText.select();
/* Copy the text inside the text field */
document.execCommand("copy");
}
</script>
<button onclick="copyToClipboardWithJavascript()">Click here</button>
</span>
</body>
</html>
I've tried the way a Javascript tutorial suggested:
我已经尝试过 Javascript 教程建议的方式:
var copyText = = document.getElementById("theList");
And my own variations using PHP within Javascript:
还有我自己在 Javascript 中使用 PHP 的变体:
var copyText = <?PHP echo($emails); ?>;
var copyText = `<?PHP echo($emails); ?>`;
var copyText = "<?PHP echo($emails); ?>";
var copyText = '<?PHP echo($emails); ?>';
But the result is that nothing causes any errors and nothing is copied to the clipboard.
但结果是没有任何错误导致任何错误并且没有任何内容被复制到剪贴板。
I know the web page is being immediately saved and used because I also make a trivial change to the letters 'Click here' in the button and can see the difference after refreshing.enter code here
我知道该网页正在立即保存和使用,因为我还对按钮中的字母“单击此处”进行了微不足道的更改,刷新后可以看到不同之处。enter code here
***UPDATE WITH ANSWER I USED:****
***更新我使用的答案:****
<span class=mono id="theList">
<?PHP echo($emails); ?>
</span>
<button id="copyButton" onclick="myCopyFunction()">Copy email address list to clipboard.</button>
<script>
function myCopyFunction() {
var myText = document.createElement("textarea")
myText.value = document.getElementById("theList").innerHTML;
myText.value = myText.value.replace(/</g,"<");
myText.value = myText.value.replace(/>/g,">");
document.body.appendChild(myText)
myText.focus();
myText.select();
document.execCommand('copy');
document.body.removeChild(myText);
}
</script>
回答by Brandon Dixon
Here is a working example I made:
这是我制作的一个工作示例:
There are two things you need to know.
有两件事你需要知道。
- Contrary to the previous answer, you CAN actually copy a variable string to the clipboard, as shown in my example.
- The user MUST EXPLICITLY take an action which causes the copy function to be called. If it is called automatically, the copy will be denied. This is most likely the cause of your problem.
- 与上一个答案相反,您实际上可以将变量字符串复制到剪贴板,如我的示例所示。
- 用户必须明确地采取导致调用复制函数的操作。如果它被自动调用,复制将被拒绝。这很可能是导致您出现问题的原因。
Here is my example. To briefly explain how this works: a new temporary element of type input type='text'is created, given the value to copy to the clipboard, then the copy command is executed, then that temporary item is removed.
这是我的例子。简要说明这是如何工作的:创建一个类型为input type='text'的新临时元素,给定要复制到剪贴板的值,然后执行复制命令,然后删除该临时项。
copyToClipboard(document.getElementById("content"));
document.getElementById("clickCopy").onclick = function() {
copyToClipboard(document.getElementById("goodContent"));
}
document.getElementById("clickCopyString").onclick = function() {
copyToClipboard("This is a variable string");
}
/**
* This will copy the innerHTML of an element to the clipboard
* @param element reference OR string
*/
function copyToClipboard(e) {
var tempItem = document.createElement('input');
tempItem.setAttribute('type','text');
tempItem.setAttribute('display','none');
let content = e;
if (e instanceof HTMLElement) {
content = e.innerHTML;
}
tempItem.setAttribute('value',content);
document.body.appendChild(tempItem);
tempItem.select();
document.execCommand('Copy');
tempItem.parentElement.removeChild(tempItem);
}
div {
border: 1px solid black;
margin: 10px;
padding: 5px;
}
<div id="content">
This is example text which will NOT be copied to the clipboard.
</div>
<div id="goodContent">
This WILL be copied to the cliboard when you push the button below:
</div>
<button id="clickCopy">
Copy Text from 2nd
</button>
<button id="clickCopyString">
Copy STRING to Clibpoard from Variable
</button>
回答by Barmar
You can't copy directly from a string, only from an HTML element. You need to put the PHP string into the value of the element.
您不能直接从字符串复制,只能从 HTML 元素复制。您需要将 PHP 字符串放入元素的值中。
function copyToClipboardWithJavascript() {
/* Get the text field */
var copyText = document.getElementById("theList");
/* Put emails into the text field */
copyText.value = <?php echo json_encode($emails); ?>;
/* Select the text field */
copyText.select();
/* Copy the text inside the text field */
document.execCommand("copy");
}

