JS复制文本到剪切板 copyText

JS复制文本到剪切板 copyText

<!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8">
        <title></title>
        <script src="https://code.jquery.com/jquery-3.1.1.min.js"></script>
    </head>
    <body>
        <span class="orange" id="shareUrl" data-url="www.baidu.com">www.baidu.com</span>

        <script>
            // 复制
            function copyText(text) {
                var textArea = document.createElement("textarea");
                // textArea.style['display']='none'
                textArea.style['position'] = 'absolute'
                textArea.style['top'] = '0'
                textArea.style['left'] = '0'
                textArea.value = text;
                document.body.appendChild(textArea);
                textArea.focus();
                textArea.select();

                try {
                    var successful = document.execCommand('copy');
                    var msg = successful ? 'successful' : 'unsuccessful';
                    console.log(msg)
                } catch (err) {
                    console.error('复制失败', err);
                }

                document.body.removeChild(textArea);
                if (successful) {
                    return true
                }
            };
            $(function() {
                var shareUrl = $("#shareUrl").data("url");
                $("#shareUrl").click(function() {
                    var shareUrl = $("#shareUrl").data("url");
                    if (copyText(shareUrl)) {
                        alert("复制成功");
                    }
                })

            })
        </script>
    </body>
</html>

 

相关文章

1.第一步 设置响应头 header(&#39;Access-Control-Allow...
$.inArray()方法介绍 $.inArray()函数用于在数组中搜索指定的...
jquery.serializejson.min.js的妙用 关于这个jquery.seriali...
JS 将form表单数据快速转化为object对象(json对象) jaymou...
jQuery插件之jquery.spinner数字智能增减插件 参考地址:http...