简体   繁体   English

使execCommand(“ Copy”)在隐藏的输入标签上工作

[英]Make execCommand(“Copy”) work on hidden input tags

I'm currently working with a function hard coded in javascript in order to copy a tag's custom address combined with a pre-defined link. 我目前正在使用用javascript硬编码的功能,以便复制标记的自定义地址和预定义的链接。 What I made is make an input type text element and set its value to what I want to copy but what happens turns out it didn't work the way I wanted to be. 我所做的是制作一个输入类型文本元素,并将其值设置为我想要复制的内容,但是事实证明,它并没有按照我想要的方式工作。 After pressing Ctrl +V, it pasted the second to the latest value in my device's clipboard. 按下Ctrl + V后,它将第二个粘贴到设备剪贴板中的最新值。 How to make execCommand("Copy") to work on a hidden input tag? 如何使execCommand(“ Copy”)在隐藏的输入标签上工作? (The function is called upon an img tag's onclick attribute) (该函数在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;

    }

PS As much a possible no jQuery please! PS尽可能没有jQuery请! Thank you. 谢谢。

The execCommand works to those elements added to the any part of the document element. execCommand适用于添加到document元素任何部分的那些元素。

the code lacks document.querySelector("body").appendChild(hiddenItem); 该代码缺少document.querySelector("body").appendChild(hiddenItem);

and can be hidden after executing the command -> hiddenItem.setAttribute("style","display: none"); 并且可以在执行命令-> hiddenItem.setAttribute("style","display: none");之后隐藏hiddenItem.setAttribute("style","display: none");

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM