↔
【JavaScript】selection から選択方向を判定する
目的
ユーザーがテキストを選択する際の方向が「左から右」なのか「右から左」なのかを判定したい。
方法
document.addEventListener('selectionchange', () => {
const selection = getSelection()
const rangeCount = selection.rangeCount
if (rangeCount === 0) {
return
}
// 複数選択を防ぐ – Firefox (Gecko)
if (rangeCount > 1) {
for (let i = 1; i < rangeCount; i++) {
selection.removeRange(selection.getRangeAt(i))
}
}
const range = selection.getRangeAt(0)
if (
selection.anchorNode === range.startContainer &&
selection.anchorOffset === range.startOffset &&
selection.focusNode === range.endContainer &&
selection.focusOffset === range.endOffset
) {
console.log('→')
}
else {
console.log('←')
}
})
解説
selection
と range
の選択方向に対する仕様の違いを利用しています。
選択方向 (→, ←)
[selection] [range]
| anchor → focus | start → end |
| focus ← anchor | start ← end |
上記の表から
- 左から右 (→):
anchor
とstart
、focus
とend
が等しい - 右から左 (←):
focus
とstart
、anchor
とend
が等しい
ということが分かるので、それをコードで表したものが下記の部分です。
if (
selection.anchorNode === range.startContainer &&
selection.anchorOffset === range.startOffset &&
selection.focusNode === range.endContainer &&
selection.focusOffset === range.endOffset
) {
console.log('→')
}
else {
console.log('←')
}
selection
と range
の対応する値は常に同一 (要検証) として片方の条件が否定された時点で方向を断定しています。
Discussion