js實現復制粘貼功能


在項目中使用到復制粘貼功能,雖然網上有很多大牛封裝了很多的插件,但是還是想不去使用插件,就像自己來實現這個功能。

另一篇是禁止復制粘貼 前端er怎樣操作剪切復制以及禁止復制+破解等


初步想法:
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 CopyClip

2. css 
.common-copy-clip {
position: relative;
textarea {
    position: absolute;
    top: 0;
    opacity: 0;
}

}

原文地址:https://segmentfault.com/a/1190000016894376


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM