将文本从<span>复制到剪贴板

时间:2018-03-12 13:10:16

标签: javascript html copy clipboard copy-paste

我一直在尝试将using UnityEngine; using System.Collections; public class ExampleClass : MonoBehaviour { public Transform target; void Update() { Vector3 relativePos = target.position - transform.position; Quaternion rotation = Quaternion.LookRotation(relativePos); transform.rotation = rotation; } } 的{​​{1}}复制到我的剪贴板而没有成功:

HTML

innerContent

的JavaScript

功能调用

<span>

功能

<span id="pwd_spn" class="password-span"></span>

我也试过了:

    document.addEventListener('DOMContentLoaded', function () {
    document.getElementById('copy').addEventListener('click', copy_password);
});

似乎function copy_password() { var copyText = document.getElementById("pwd_spn").select(); document.execCommand("Copy"); } function copy_password() { var copyText = document.getElementById("pwd_spn").textContent; copyText.select(); document.execCommand("Copy"); } 元素不起作用,因为我在两者上都出现以下错误:

enter image description here

3 个答案:

答案 0 :(得分:14)

您可以这样做:创建一个临时文本区域并将其附加到页面,然后将span元素的内容添加到文本区域,从文本区域复制值并删除文本区域。

由于某些安全限制,如果用户与页面进行了互动,您只能执行Copy命令,因此您必须在用户点击按钮后添加按钮并复制文本。

&#13;
&#13;
document.getElementById("cp_btn").addEventListener("click", copy_password);

function copy_password() {
    var copyText = document.getElementById("pwd_spn");
    var textArea = document.createElement("textarea");
    textArea.value = copyText.textContent;
    document.body.appendChild(textArea);
    textArea.select();
    document.execCommand("Copy");
    textArea.remove();
}
&#13;
<span id="pwd_spn" class="password-span">Test</span>
<button id="cp_btn">Copy</button>
&#13;
&#13;
&#13;

答案 1 :(得分:2)

请参阅https://stackoverflow.com/a/48020189/2240670,有一段代码可以为您提供div的示例,这也适用于跨度,我没有在此处复制它以避免重复。

基本上,当您要复制到剪贴板时,您需要创建一系列文本,<textarea><input>元素可以轻松实现这一点,因为它们具有select()方法,但如果您是尝试从<div><span>等任何其他类型的元素复制内容时,您需要:

  1. 创建/获取Range对象(某些浏览器不提供构造函数,或者是一种不错的方法来执行此操作)。调用document.getSelection().getRangeAt(0),我发现除了edge之外的大多数浏览器都可以使用(即11可以工作)。
  2. 将要复制的元素添加到该范围的选择中。
  3. 将该范围添加到窗口或文档Selection
  4. 致电document.execCommand("copy")复制所选文字。
  5. 我还建议您查看SelectionRange的API,以便更好地掌握这一点。

答案 2 :(得分:0)

简单方法
1)创建输入
2)赋予样式 z-index -1 ,它将被隐藏

    var code = $("#copy-to-clipboard-input");
    var btnCopy = $("#btn-copy");

    btnCopy.on("click", function () {
        code.select();
        document.execCommand("copy");
    });
                                                                                             
<input type="input" style="width:10px; position:absolute; z-index: -100 !important;" value="hello" id="copy-to-clipboard-input">
<button class="btn btn-success" id="btn-copy">Copy</button>

相关问题