houjl

今天开发一个需求的时候 遇见一个功能 ,需要点击按钮复制一个文本, ctrl+v能粘贴出来

我们直接上代码

<!DOCTYPE html>
<html>
<head>
    <script>
        // 复制函数
        // str是复制的文字
        function copyText(str) {
            var save = function (e) {
                e.clipboardData.setData(\'text/plain\', str);
                e.preventDefault();
            };
            document.addEventListener(\'copy\', save);
            document.execCommand(\'copy\');
            document.removeEventListener(\'copy\', save);
            console.log(\'复制成功\');
        }
    </script>
</head>
<body>
    <button onclick="copyText(22222222)">复制文本</button>
</body>

</html>

这样我们就可以复制出来啦!!!

分类:

技术点:

相关文章: