我正在尝试在 Angular 应用中使用 JS 将内容复制到剪贴板。
不幸的是,document.queryCommandEnabled("copy")
将始终返回 false
。有什么办法可以理解为什么浏览器拒绝执行命令?启用命令的标准是什么?
代码:
function copyText(text) {
var input = document.createElement('textarea');
document.body.appendChild(input);
input.value = text;
input.focus();
input.select();
var success = document.execCommand('Copy');
input.remove();
return success;
}
我在运行这个函数之前测试命令是否启用:
if(document.queryCommandEnabled("copy")) // Always return false
executeCopy(text_value);
最佳答案
document.queryCommandEnabled ("copy") 命令在有选择时返回真,否则返回假
function doCopy(){
if(document.queryCommandEnabled("copy")){
copyText("Hola")
}else{
alert("Never Fired");
}
}
function copyText(text) {
var input = document.createElement('textarea');
document.body.appendChild(input);
input.value = text;
input.focus();
input.select();
var success = document.execCommand('Copy');
input.remove();
}
<html>
<head></head>
<body>
<input type="button" onclick="doCopy('Herman')" value="s">
</body>
</html>
我们必须做出选择才能使其正常工作
function copyText(text) {
var input = document.createElement('textarea');
document.body.appendChild(input);
input.value = text;
input.focus();
input.select();
if(document.queryCommandEnabled("copy")){
var success = document.execCommand('Copy');
input.remove();
alert("Copy Ok");
}else{
alert("queryCommandEnabled is false");
}
}
<html>
<head></head>
<body>
<input type="button" onclick="copyText('Herman')" value="s">
</body>
</html>
根据 Blundering Philosopher 的评论,使用 document.queryCommandSupported(command);验证命令是否可以在浏览器实例中运行
function doCopy(){
if(document.queryCommandSupported("copy")){
copyText("Hello")
}else{
alert("Never Fired");
}
}
function copyText(text) {
var input = document.createElement('textarea');
document.body.appendChild(input);
input.value = text;
input.focus();
input.select();
var success = document.execCommand('Copy');
input.remove();
alert("Copy Ok");
}
<html>
<head></head>
<body>
<input type="button" value="Copy" onclick="doCopy()">
</body>
</html>
关于javascript - 找出 queryCommandEnabled 返回 false 的原因,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35719922/