博客园

super.hill

记录搬砖中遇到的坑,欢迎批评指导!

  博客园 :: 首页 :: 博问 :: 闪存 :: 新随笔 :: 联系 :: 订阅 订阅 :: 管理 ::

js 复制文本到剪贴板

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <title>点击复制到剪贴板</title>
</head>

<body>
    <div id="app">
        <p>博客园是最棒的!</p>
        <button id="copy">点击复制</button>
    </div>
    <script>
        var btn = document.getElementById('copy');
        var val = document.getElementsByTagName('p')[0].innerText;
        
        btn.onclick = function(){
            var tempInput  = document.createElement('input');
            tempInput.value = val;
            document.body.appendChild(tempInput );
            tempInput.select(); // 选择对象
            document.execCommand("Copy"); // 执行浏览器复制命令
            tempInput.className = 'tempInput ';
            tempInput.style.display='none';
            document.body.removeChild(tempInput );//移除
        }

    </script>
</body>

</html>

 

posted on 2018-05-11 16:07  超岭  阅读(173)  评论(0编辑  收藏  举报
博客园