画面上で選択されている範囲に特定のNodeが含まれているか検証するにはSelection.containsNode()を使用します。
import { useCallback, useEffect, useRef } from 'react'
export function Sample() {
const ref = useRef<HTMLParagraphElement>(null)
const handleSelectionChange = useCallback(() => {
const paragraph = ref.current
const selection = document.getSelection()
if (paragraph) {
console.log(selection?.containsNode(paragraph, true)) // 選択範囲に<p></p>が含まれていればtrue
}
}, [])
useEffect(() => {
document.addEventListener('selectionchange', handleSelectionChange)
return () => {
document.removeEventListener('selectionchange', handleSelectionChange)
}
}, [handleSelectionChange])
return (
<p ref={ref}>
サンプルのテキスト。サンプルのテキスト。サンプルのテキスト。サンプルのテキスト。サンプルのテキスト。
</p>
)
}