js实现点击按钮复制某个元素的值-综合编程教学论坛-语言编程-源码交易网

js实现点击按钮复制某个元素的值

日常开发中js实现点击按钮一键复制内容的方法很多,比如使用使用 document.execCommand() 方法。也可以使用使用 Clipboard API,还可以使用第三方库,例如 Clipboard.js,下边我们说最简单的一种原始方法。

705d4da97a20241123115005

 

HTML代码

1
2
3
4
<div>
    <text type="text" id="copyContent">这是要复制的内容</text>
    <input onclick="copyLink();" value="一键复制" type="button"></input>
</div>

JS代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
<script type="text/Javascript"
function copyLink(){
    const copyContent = document.getElementById("copyContent").innerText;
    const textarea = document.createElement('textarea');
    textarea.value = copyContent;
    document.body.appendChild(textarea);
 
    textarea.select(); // 选择对象
    try {
       const result = document.execCommand('copy');
       if (result) {
         alert('复制成功!');
         console.log('复制成功')
       else {
         console.error('复制失败!');
        }
         catch (error) {
         console.error('复制错误:', error);
       }
           
         // 移除元素
       textarea.remove();
    
</script>

原创不易,转载请注明出处!