在项目中使用到复制粘贴功能,虽然网上有很多大牛封装了很多的插件,但是还是想不去使用插件,就像自己来实现这个功能。
初步想法:1. 获取到需要复制的内容,这里我可以将需要复制的内容放在input或者textarea的value中,然后使用input的select()方法来获取到值;2. 获取到值了,那我下一步就是复制了,document.execCommand()方法可以操作很多功能,这里我可以使用他的copy复制选中的文字到粘贴板的功能;3. 复制功能实现了,但是这个input或者textarea不是我页面布局中所需要的,那我可以将input或者textarea设置成透明的;代码实现:1. js: import React, {PureComponent} from 'react'; import PropTypes from 'prop-types'; import './index.less' class CopyClip extends PureComponent { static propTypes = { text: PropTypes.any, //文字内容 ID: PropTypes.string }; static defaultProps = { ID: 'copy-clip-textarea', }; constructor(props) { super(props); this.state = {} } componentWillMount() { const {text} = this.props; this.setState({ text }) } componentWillReceiveProps(nextProps) { const {text} = nextProps; this.setState({ text }) } handleCopy = () => { let {ID} = this.props; let range, selection; let input = document.getElementById(ID); input.select(); // 获取到需要复制的内容 if (input.value && ((typeof input.select) == 'function')) { range = document.createRange(); // 创建range对象 selection = document.getSelection(); // 返回一个Selection 对象,表示用户选择的文本范围或光标的当前位置。 range.selectNode(input); selection.addRange(range); input.setSelectionRange(0, input.value.length); // 为当前元素内的文本设置备选中范围 let successful = document.execCommand('copy'); // 使用document.execCommand()方法, copy指令复制选中的文字到粘贴板的功能 if (!successful) { this.props.onCopy(false); window.clipboardData.setData('text', this.state.text); // 解决部分浏览器复制之后没有粘贴到粘贴板,使用浏览器自带的粘贴板 } else { this.props.onCopy(true) } } else { this.props.onCopy(false) } }; render() { const {text} = this.state; return (this.handleCopy()}> {this.props.children}) } } export default CopyClip2. css .common-copy-clip {position: relative;textarea { position: absolute; top: 0; opacity: 0;}
}