300字范文,内容丰富有趣,生活中的好帮手!
300字范文 > js实现复制粘贴功能

js实现复制粘贴功能

时间:2019-03-31 14:29:39

相关推荐

js实现复制粘贴功能

在项目中使用到复制粘贴功能,虽然网上有很多大牛封装了很多的插件,但是还是想不去使用插件,就像自己来实现这个功能。

初步想法: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 (<div className="common-copy-clip" onClick={() => this.handleCopy()}><textarea readOnly="readonly" id={this.props.ID} value={text}></textarea>{this.props.children}</div>)}}export default CopyClip2. css .common-copy-clip {position: relative;textarea {position: absolute;top: 0;opacity: 0;}

}

原文地址:/a/1190000016894376

更多专业前端知识,请上【猿2048】

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。