点击复制代码,通过JS,点击后可直接复制预设内容到剪切板!

在网页设计的时候,有时候为了用户体验,需要让用直接点击即可复制代码或别的文本内容
电脑屋小编是为了让用户可复制淘口令的时候才需要的!
经过各种淘,终于找到这一段手机电脑都可以使用的代码!

<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8"> 
    <title>复制</title>
</head>
<body>
    <script>  
           var textCopy=function (data) {
                var f=document.createElement("form");
                f.id="copy-"+Date.parse(new Date());
                f.onsubmit=function(){return false};
                f.style="opacity: 0;height: 1px;width: 1px;overflow: hidden;position:fixed;top: -1;left: -1;z-index: -1;"
                f.innerHTML=`<button onclick='story.select();document.execCommand("Copy");'></button>
                <textarea name="story">${data}</textarea>`;
                document.body.appendChild(f);
                document.querySelector(`#${f.id}>button`).click();  
                document.body.removeChild(document.getElementById(f.id));
            } 
    </script>
    <input id="test"  value="" />
    <button onclick="textCopy(document.getElementById('test').value)" >复制</button>    
</body>
</html>
本文链接:https://www.dnwfb.com/1533.html,转载请注明出处。
0

评论0

没有账号? 注册  忘记密码?