zoukankan      html  css  js  c++  java
  • 纯js实现复制内容到剪切板

    下面的方法可以完美实现:

    1. 复制指定input 或者 textarea中的内容;
    2. 指定非输入框元素中的内容

    代码如下:

    function copyToClipboard(elem) {
        // create hidden text element, if it doesn't already exist
        var targetId = "_hiddenCopyText_";
        var isInput = elem.tagName === "INPUT" || elem.tagName === "TEXTAREA";
        var origSelectionStart, origSelectionEnd;
        if (isInput) {
            // can just use the original source element for the selection and copy
            target = elem;
            origSelectionStart = elem.selectionStart;
            origSelectionEnd = elem.selectionEnd;
        } else {
            // must use a temporary form element for the selection and copy
            target = document.getElementById(targetId);
            if (!target) {
                var target = document.createElement("textarea");
                target.style.position = "absolute";
                target.style.left = "-9999px";
                target.style.top = "0";
                target.id = targetId;
                document.body.appendChild(target);
            }
            target.textContent = elem.textContent;
        }
        // select the content
        var currentFocus = document.activeElement;
        target.focus();
        target.setSelectionRange(0, target.value.length);
     
        // copy the selection
        var succeed;
        try {
            succeed = document.execCommand("copy");
        } catch(e) {
            succeed = false;
        }
        // restore original focus
        if (currentFocus && typeof currentFocus.focus === "function") {
            currentFocus.focus();
        }
     
        if (isInput) {
            // restore prior selection
            elem.setSelectionRange(origSelectionStart, origSelectionEnd);
        } else {
            // clear temporary content
            target.textContent = "";
        }
        return succeed;
    }
    
    //我们可以这样直接调用这个方法:
    
    //copyToClipboard(document.getElementById("name"));
    

    代码来自:通过按钮直接把input或者textarea里的值复制到粘贴板里

  • 相关阅读:
    Python学习-字符编码浅析
    python元组,集合类型,及字典补充
    python字符串,列表常用操作
    python流程控制
    Python之线程&进程
    yii框架的中的一些使用介绍
    《最牛B的Linux Shell命令》笔记
    CentOS6.8上安装epel
    mysql 5.7 Group Replication
    mysql5.7 参数记录 (持续更新)
  • 原文地址:https://www.cnblogs.com/martinl/p/9853030.html
Copyright © 2011-2022 走看看