[JS] js copy text

copy code

src/util/copy.js

/**
 * @txt {String}  复制的文本
 * @return {Boolean} 复制成功:true 复制失败:false   
*/
const copy = txt => {
    
    
    const textareaC = document.createElement('textarea');
    textareaC.setAttribute('readonly', 'readonly'); //设置只读属性防止手机上弹出软键盘
    textareaC.value = txt;
    document.body.appendChild(textareaC); //将textarea添加为body子元素
    textareaC.select();

    const res = document.execCommand('copy');
    document.body.removeChild(textareaC);//移除DOM元素 
    return res;
}

export default copy 

use in vue

home.vue

<template>
	<button @click='copy(copyTxt)'>点我复制</button >
</template>
<script setup>
// 导入复制函数
import copy from '@util/copy'

const copyTxt = '我是被复制的内容'
</script>

Guess you like

Origin blog.csdn.net/qq_43614372/article/details/130861282