如題,咱們怎麼在React或者其餘的框架中實現一鍵複製呢,實際上實現一鍵複製的代碼與框架無關,由於他是用的是原生的API,下面咱們用React來實現一下css
效果:react
核心代碼:antd
直接將紅框處改成須要複製的元素類名。(獲取元素時注意一下我用的是querySelector)框架
將該事件綁定到元素上,便可。完整代碼在最下方this
完整代碼:spa
注意:Icon和message均是來自於antd組件庫,如若沒裝antd,改爲別的元素便可3d
import React from 'react'; import './App.css'; import {Icon, message} from 'antd'; class App extends React.Component{ //一鍵複製功能 copy() { const copyEle = document.querySelector('.contentText') // 獲取要複製的節點 const range = document.createRange(); // 創造range window.getSelection().removeAllRanges(); //清除頁面中已有的selection range.selectNode(copyEle); // 選中須要複製的節點 window.getSelection().addRange(range); // 執行選中元素 const copyStatus = document.execCommand("Copy"); // 執行copy操做 // 對成功與否認進行提示 if (copyStatus) { message.success('複製成功'); } else { message.fail('複製失敗'); } window.getSelection().removeAllRanges(); //清除頁面中已有的selection } render() { return ( <div className="App"> <div className="content"> <p className="contentTitle"> <Icon type="copy" onClick={this.copy}/> </p> <p className="contentText"> 我是要被複制的內容啊!!! </p> </div> </div> ); } } export default App;
原理:code
咱們來看一下具體的步驟:(具體API使用能夠查閱MDN)對象
1. document.querySelector('.contentText') 獲取須要複製的節點blog
2. document.createRange(); 創造一個區域
3. window.getSelection().removeAllRanges(); 將全部選區都清除(即被按住鼠標劃中選擇的部分)
4. range.selectNode(copyEle); 選中區域要包含的對象
5. document.execCommand("Copy"); execCommand方法容許運行命令來操縱可編輯內容區域的元素。
6.判斷成功與否
7.window.getSelection().removeAllRanges(); 將全部選區都清除(即被按住鼠標劃中選擇的部分)
經過以上的步驟,一鍵複製就作好啦!!