兼容性
IE9以上基本都已經(jīng)支持該API

Paste_Image.png
selection 實(shí)例
- 獲取selction
window.selection方法 -
anchor用戶操作開始的地方 -
focus用戶操作結(jié)束的地方 -
range是包含element文本節(jié)點(diǎn)的html片段,通常來說用戶選擇的selection包含一個(gè)range實(shí)例, 多實(shí)例的功能只有火狐支持。
實(shí)例屬性
| 屬性名稱 | 類型 | 描述 |
|---|---|---|
| anchorNode | NodeElement | 用戶選擇區(qū)域開始的節(jié)點(diǎn) |
| anchorOffset | Number | 如果anchorNode是文本節(jié)點(diǎn),anchorOffset表示用戶選擇開始的字符相對(duì)節(jié)點(diǎn)內(nèi)容首個(gè)字符的偏移,如果是element 則表示,該節(jié)點(diǎn)相對(duì)element子元素的位置。 |
| forcusNode | NodeElement | 用戶選擇區(qū)域結(jié)束的節(jié)點(diǎn) |
| forcusOffset | Number | 如果forcusNode是文本節(jié)點(diǎn),forcusOffset表示用戶選擇開始的字符相對(duì)節(jié)點(diǎn)內(nèi)容首個(gè)字符的偏移,如果是element 則表示,該節(jié)點(diǎn)相對(duì)element子元素的位置。 |
| isCollapsed | Boolean | 用戶操作的起始點(diǎn)和終點(diǎn)是否重合(可以用來判斷是否是有效操作,為true時(shí)表示取消操作) |
| rangeCount | Number | 返回選區(qū)內(nèi)range的個(gè)數(shù) |
實(shí)例方法
下面介紹的方法是chrome已經(jīng)支持的方法
- getRangeAt() 返回 當(dāng)全選中的range對(duì)象中的某一個(gè)
- collapse(parentNode, offset)銷毀現(xiàn)有的
selection實(shí)例并用parentNode.childNodes[offset]作為anchor和focus生成新的selection來替換。 - extend(parentNode, offset) 移動(dòng)
focus到指定位置不改變anchor
var sel = window.getSelection();
sel.extend(sel.focusNode, sel.focusOffset + 5);
- selectAllChildren(parentNode)
parentNode的所有子元素被加入到selection中替換掉了原有的。 - deleteFromDocument() 從document中刪除
- toString 返回當(dāng)前被選中的內(nèi)容的文本
- containsNode(aNode,aPartlyContained) 表明文本aNode是否在Seleciton中 aPartlyContained === false 要求aNode必須在seleciton中 aPartlyContained === true 部分在即可
window.getSelection().containsNode(document.body, true)
>>true
復(fù)制內(nèi)容到剪貼板
// 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隱藏, 可以定位到可視區(qū)域的外面。
// 雙擊復(fù)制內(nèi)容組件
// @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: '復(fù)制內(nèi)容到剪貼板失敗'
})
}
}
render(){
return (
<div onDoubleClick={this.select} ref={el => this.rootEl = el}>
{this.props.children}
</div>
)
}
}
export default SelectAllText;