使execCommand(“Copy”)处理隐藏的输入标记

时间:2017-11-02 12:03:20

标签: javascript php input hidden-field execcommand

我目前正在使用javascript中硬编码的函数来复制标记的自定义地址并结合预定义的链接。我做的是创建一个输入类型的文本元素,并将其值设置为我想要复制的内容,但结果发现它不能按照我想要的方式工作。按Ctrl + V后,它会将第二个值粘贴到设备剪贴板中的最新值。 如何使execCommand(“Copy”)处理隐藏的输入标记? (该函数在img标签的onclick属性上调用)

function shareFile() {
        var hiddenItem = document.createElement("input");
        hiddenItem.type = "text";
        hiddenItem.setAttribute("style","display: none");
        hiddenItem.value = <?php echo (isset($_SERVER['HTTPS'])?"\"https://":"\"http://").$_SERVER['SERVER_NAME']."/filesystem/openfile.php?dir=\" + " ?> encodeURI(this.parentNode.parentNode.parentNode.getAttribute("r-directory"));
        hiddenItem.select();
        console.log(hiddenItem.value);
        document.execCommand("Copy");
        // location.href = "resources.php?smsg=The file's link has been successfully copied to your clipboard." <?php if (!empty($_GET['dir'])) echo " + \"&dir=".$_GET['dir']."\""?>;
        return false;

    }

P.S。尽可能多的jQuery请!谢谢。

1 个答案:

答案 0 :(得分:0)

execCommand 适用于添加到文档元素任意部分的元素。

代码缺少document.querySelector("body").appendChild(hiddenItem);

并且可以在执行命令后隐藏 - &gt; hiddenItem.setAttribute("style","display: none");