1. 程式人生 > >js實現複製貼上功能

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 CopyClip

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

}

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