光标选区API Selection

2017-02-12  本文已影响162人  溪离欣洛

兼容性

IE9以上基本都已经支持该API

Paste_Image.png

selection 实例

实例属性

属性名称 类型 描述
anchorNode NodeElement 用户选择区域开始的节点
anchorOffset Number 如果anchorNode是文本节点,anchorOffset表示用户选择开始的字符相对节点内容首个字符的偏移,如果是element 则表示,该节点相对element子元素的位置。
forcusNode NodeElement 用户选择区域结束的节点
forcusOffset Number 如果forcusNode是文本节点,forcusOffset表示用户选择开始的字符相对节点内容首个字符的偏移,如果是element 则表示,该节点相对element子元素的位置。
isCollapsed Boolean 用户操作的起始点和终点是否重合(可以用来判断是否是有效操作,为true时表示取消操作)
rangeCount Number 返回选区内range的个数

实例方法

下面介绍的方法是chrome已经支持的方法

var sel = window.getSelection();
sel.extend(sel.focusNode, sel.focusOffset + 5);
window.getSelection().containsNode(document.body, true)
>>true

复制内容到剪贴板

// preViewEl: HTMLParagraphElement;
copy = (e: Event) => {
   let range,
       selection;
   try{
       selection = window.getSelection();
       range = document.createRange();
       range.selectNodeContents(this.preViewEl);
       selection.removeAllRanges();
       selection.addRange(range);
       document.execCommand('copy');
       this.preViewEl.blur();
   }catch(e){
       debugger;
   }
}

注意
preViewEl 一定是需要展示在页面上的元素,不能使用display隐藏, 可以定位到可视区域的外面。

// 双击复制内容组件

// @flow
import React, { Component } from 'react';

class SelectAllText extends Component{
    props: {
        children: ReactElement
    };
    rootEl: HTMLDivElement;
    select = (e) =>{
        try{
            const selection = window.getSelection();
            const range = document.createRange();
            const targetEl = this.rootEl.firstElementChild;
            if (!targetEl) return;
            range.selectNodeContents(targetEl);
            selection.removeAllRanges();
            selection.addRange(range);
            document.execCommand('copy');
            targetEl.blur();
        }catch(e){
            $.message.show({
                type: 'error',
                msg: '复制内容到剪贴板失败'
            })
        }
    }
    render(){
        return (
            <div onDoubleClick={this.select} ref={el => this.rootEl = el}>
                {this.props.children}
            </div>
        )
    }
}
export default SelectAllText;
上一篇下一篇

猜你喜欢

热点阅读