微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

javascript – 找出queryCommandEnabled返回false的原因

我试图在角度应用程序中使用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”)命令返回true,否则返回false
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>

原文地址:https://www.jb51.cc/js/157386.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐