让自己的网站添加复制功能JS代码如下:
第一种
- <script>
- $(function () { var id = 0;
- $(“pre“).each(function () {
- $(this).attr(“id“, ++id).attr(“ondblclick“, ‘copycode(‘ + id + ‘)‘);
- })
- }); function copycode(i) { const range = document.createRange();
- range.selectNode(document.getElementsByTagName(‘pre‘)[i – 1]); const selection = window.getSelection(); if (selection.rangeCount > 0) selection.removeAllRanges();
- selection.addRange(range); document.execCommand(‘copy‘);
- alert(“复制成功“)
- }</script>
第二种
- <script>
- function Toast(msg,duration){
- duration=isNaN(duration)?3000:duration; var m = document.createElement(‘div‘);
- m.innerHTML = msg;
- m.style.cssText=“max–width:60%;min–width: 150px;padding:0 14px;height: 40px;color: rgb(255, 255, 255);line–height: 40px;text–align: center;border–radius: 4px;position: fixed;top: 50%;left: 50%;transform: translate(-50%, –50%);z–index: 999999;background: rgba(0, 0, 0,.7);font–size: 16px;“; document.body.appendChild(m);
- setTimeout(function() { var d = 0.5;
- m.style.webkitTransition = ‘-webkit–transform ‘ + d + ‘s ease–in, opacity ‘ + d + ‘s ease–in‘;
- m.style.opacity = ‘0‘;
- setTimeout(function() { document.body.removeChild(m) }, d * 1000);
- }, duration);
- }
- </script>
评论0