JS复制粘贴 | Vue 复制粘贴 | React 复制粘贴

in 前端 with 0 comment

JS 一键复制粘贴

以此 HTML 为基准

<div class="copyNode" contenteditable="true">点我进行复制</div>

原生写法 1

const copyNode = document.querySelector('.copyNode');
copyNode.addEventListener('copy', (event) => {
    const selection = document.getSelection();
    event.clipboardData.setData('text/plain', selection.toString().toUpperCase());
    event.preventDefault();
    console.log("复制成功!")
});

原生写法 2

const copyNode = document.querySelector('.copyNode');
copyNode.addEventListener('click', (event) => {
    navigator.clipboard.writeText("我是复制的东西")
    console.log("复制成功!")
});

Vue 包

https://www.npmjs.com/package/vue-clipboard2

React 包

https://www.npmjs.com/package/copy-to-clipboard

Comments are closed.