js实现复制内容到粘贴板

 1 <!DOCTYPE html>
 2 <html>
 3   <head>
 4     <meta charset="utf-8" />
 5     <title>js复制内容到粘贴板</title>
 6     <style>
 7       .flex-r {
 8         display: flex;
 9         flex-direction: row;
10         align-content: center;
11         justify-content: space-between;
12       }
13       .info {
14           max-width: 400px;;
15         margin-bottom: 20px;
16         background-color: bisque;
17       }
18       dl {
19         margin: 0;
20         padding: 0 30px;
21         width: 200px;
22       }
23       .copy{
24         cursor: pointer;
25         margin: 0 10px;
26       }
27     </style>
28   </head>
29 
30   <body>
31     <div class="bank_info">
32       <div class="flex-r info">
33         <dl class="flex-r aln-star">
34           <dt>收款银行:</dt>
35           <dd>建设银行</dd>
36         </dl>
37         <span class="copy" onclick="mmcopy(this)">复制</span>
38       </div>
39       <div class="flex-r info">
40         <dl class="flex-r aln-start">
41           <dt>收款账户名:</dt>
42           <dd>张三</dd>
43         </dl>
44         <span class="copy" onclick="mmcopy(this)">复制</span>
45       </div>
46     </div>
47 
48     <!--引入jQuery插件 -->
49     <script src="https://cdn.bootcss.com/jquery/3.3.0/jquery.min.js"></script>
50     <script>
51       function mmcopy(e) {
52         if (document.execCommand("copy")) {
53           var txt = ""; // 需要复制的文字
54           txt += $(e)
55             .siblings("dl")
56             .find("dt")
57             .text();
58           txt += $(e)
59             .siblings("dl")
60             .find("dd")
61             .text();
62           const input = document.createElement("input"); // 创建一个新input标签
63           input.setAttribute("readonly", "readonly"); // 设置input标签只读属性
64           input.setAttribute("value", txt); // 设置input value值为需要复制的内容
65           document.body.appendChild(input); // 添加input标签到页面
66           input.select(); // 选中input内容
67           input.setSelectionRange(0, 9999); // 设置选中input内容范围
68           document.execCommand("copy"); // 复制
69           document.body.removeChild(input);  // 删除新创建的input标签
70         }
71       }
72     </script>
73   </body>
74 </html>

猜你喜欢

转载自www.cnblogs.com/zhenguo-chen/p/10454521.html