点击按钮复制到剪贴板 js

时间:2021-02-26 19:36:34
<span style="font-family: Arial, Helvetica, sans-serif;">案例一:</span>
</pre><pre code_snippet_id="1755225" snippet_file_name="blog_20160711_1_4917192" name="code" class="html"><!DOCTYPE html><html lang="en"><head>	<meta charset="UTF-8">	<meta name="viewport" content="width=device-width, initial-scale=1">	<title>Document</title></head><body>	<script data-cfhash='f9e31' type="text/javascript">                  function jsCopy(){                    var e=document.getElementById("copy-num");//对象是copy-num1                    e.select(); //选择对象                    document.execCommand("Copy"); //执行浏览器复制命令                    alert("复制成功");                }                  /* <![CDATA[ */                  !                  function() {                    try {                      var t = "currentScript" in document ? document.currentScript: function() {                        for (var t = document.getElementsByTagName("script"), e = t.length; e--;) if (t[e].getAttribute("data-cfhash")) return t[e]                      } ();                      if (t && t.previousSibling) {                        var e, r, n, i, c = t.previousSibling,                        a = c.getAttribute("data-cfemail");                        if (a) {                          for (e = "", r = parseInt(a.substr(0, 2), 16), n = 2; a.length - n; n += 2) i = parseInt(a.substr(n, 2), 16) ^ r,                          e += String.fromCharCode(i);                          e = document.createTextNode(e),                          c.parentNode.replaceChild(e, c)                        }                        t.parentNode.removeChild(t);                      }                    } catch(u) {}                  } ()                  /* ]]> */                                  </script>				 <div class="nav navbar-top-links navbar-right">                  <li>推广链接:</li>                                     <li><input id="copy-num" class="form-control" type="text" value="" style="max-width:100px;display:inline-block;color: #999; margin-top:12px"></li>                    <li><button onClick="jsCopy()" type="button" class="btn btn-sm">复制</button></li>                                 </div></body></html>


案例二:

<html>
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Zero Clipboard Test</title>
</script>
</head>
<body>
<script type="text/javascript">
function jsCopy(){
var e=document.getElementById("contents");//对象是contents
e.select(); //选择对象
tag=document.execCommand("Copy"); //执行浏览器复制命令
if(tag){
alert('复制内容成功');
}
}

</script>
<textarea id="contents" cols="40" rows="5"></textarea>
<br />
<input type="button" onClick="jsCopy();" value="复制" />
</body>
</html>

以上都可以执行,亲自测试!