• js点击按钮复制内容到粘贴板


    复制内容到粘贴板,就是要选择需要复制的内容并执行document.execCommand("copy")命令:

    //复制内容到粘贴板
    function copyToClipboard(elemId) {
        var target = document.getElementById(elemId);
        // 选择内容
        target.focus();
        target.setSelectionRange(0, target.value.length);
        // 复制内容
        var succeed;
        try {
            succeed = document.execCommand("copy");
        } catch (e) {
            succeed = false;
        }
        console.log("复制成功");
        return succeed;
    }

    如果应用场景复杂些,可能有多种元素(textarea、input、div等)需要复制内容,可以写一个通用方法:

    //复制内容到粘贴板
    function copyToClipboard(elemId) {
        var elem = document.getElementById(elemId);
        var targetId = "_hiddenCopyText_";
        var isInput = elem.tagName === "INPUT" || elem.tagName === "TEXTAREA";
        var origSelectionStart, origSelectionEnd;
        if (isInput) {
            // 复制选择内容
            target = elem;
            origSelectionStart = elem.selectionStart;
            origSelectionEnd = elem.selectionEnd;
        } else {
            // 必须有一个临时的元素存储复制的内容
            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;
        }
        // 选择内容
        var currentFocus = document.activeElement;
        target.focus();
        target.setSelectionRange(0, target.value.length);
        // 复制内容
        var succeed;
        try {
            succeed = document.execCommand("copy");
        } catch (e) {
            succeed = false;
        }
        // 恢复焦点
        if (currentFocus && typeof currentFocus.focus === "function") {
            currentFocus.focus();
        }
        if (isInput) {
            // 恢复之前的选择
            elem.setSelectionRange(origSelectionStart, origSelectionEnd);
        } else {
            // 清除临时内容
            target.textContent = "";
        }
        console.log("复制成功");
        return succeed;
    }
  • 相关阅读:
    XML中对于一个books.xml的详情显示,删除按钮,修改并保存按钮 和 添加按钮。完成这些按钮所对应的功能(XmlDocument)。
    如何写一个验证码
    Binary Search
    数据库排行榜
    mac os 下 sublime text 2 和 iterm2 便捷配置
    HttpGet,HttpPost,HttpPut,HttpDelete
    Compile C/C++ In Eclipse for Android
    To Use EGit(Git for Eclipse)
    Android NDK about Library (static library , share library and 3rd party library)
    Dealing with bitmap object in android NDK
  • 原文地址:https://www.cnblogs.com/yeqrblog/p/9964550.html
Copyright © 2020-2023  润新知