![](/img/trans.png)
[英]Best way to select/highlight text (in text input) in Vue (using computed properties for value and selection range)
[英]Select Text & highlight selection or get selection value (React)
使用onMouseUp
和onDoubleClick
事件來檢測調用方法,這將使用 JavaScript Selection API 確定選擇。
使用window.getSelection()
獲取選擇對象。
要獲取選定的文本,請使用window.getSelection.toString()
。
要獲取用於呈現彈出菜單的選定文本區域的坐標,請使用selection.getRangeAt(0).getBoundingClientRect()
。
作為示例實現,請查看react-highlight庫。
我認為這是正確的方法...
document.onmouseup = () => {
console.log(window.getSelection().toString());
};
這是 React 中使用函數式組件的示例:
const Post = () => {
const handleMouseUp() {
console.log(`Selected text: ${window.getSelection().toString()}`);
}
return (
<div onMouseUp={handleMouseUp}>Text</div>
);
}
正如 Lyubomir 指出的,window.getSelection() API 可以解決問題!
第 1 步: - 最初每次輸入內容時,鼠標都會捕獲
<textarea type="text"
className="contentarea__form__input"
onMouseUpCapture={this.selectedText}>
</textarea>
第 2 步:為了確保它只捕獲您選擇的文本,我使用了 if-else 條件
selectedText = () => {
window.getSelection().toString() ? console.log(window.getSelection().toString()) : null;
}
由於Firefox 中的這個錯誤,我無法按照其他答案的建議使用window.getSelection()
。
所以我必須執行以下操作(在 React 中):
constructor(props) {
this.textAreaRef = React.createRef();
}
getSelection() {
const textArea = (this.textAreaRef.current as HTMLTextAreaElement);
console.log(textArea.value.substring(
textArea.selectionStart,
textArea.selectionEnd
)
);
}
render() {
<textarea onMouseUp={() => this.getSelection()}
ref={this.textAreaRef}>
</textarea>
}
我剛剛為此做了一個自定義鈎子(如果需要,在打字稿中):
export const useSelectedText = () => {
const [text, setText] = useState('')
const select = () => {
const selected = window.getSelection() as Selection
setText(selected.toString())
}
return [select, text] as const
}
這可以使用react-text-annotate
庫來完成: https : //www.npmjs.com/package/react-text-annotate
我們可以簡單地使用 state 來選擇和突出顯示它們。
import styled from 'styled-components';
const ClipBoardLink = styled.span<{ selection: boolean }>`
background: ${(p) => (p.selection ? '#1597E5' : '')};
margin-left: 0.5rem;
color: ${(p) => (p.selection ? '#fff' : '')};
`;
const GroupOrderModel = () => {
const [isCopied, setIsCopied] = useState(false);
const handleIsClipboardCopy = async (text: string) => {
setIsCopied(true);
navigator.clipboard.writeText(text);
setTimeout(() => {
setIsCopied(false);
}, 5000);
};
return (
<ClipBoardLink selection={isCopied} onClick={async () => await handleIsClipboardCopy("Click me!")}>Click me!</ClipBoardLink>
);
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.