デモ
次のCodePenの文章上をマウスを左クリックして、文字を選択してみてください。
選択した部分が黄色く残ります。
See the Pen マウス選択した文字をマークする by shigeru.nakajima (@ledsun) on CodePen.
実装
黄色
選択した文字を黄色くするにはmarkタグを使います。
markタグの追加
テキストが選択されたら、JavaScriptでmarkタグを追加します。
選択領域の取得にはSelectionを使います。
指定した範囲をタグで囲うにはRange.surroundContentsを使います。
const text = document.querySelector('.text')
// text でなく document.body を監視しないと
// 選択領域上でmouseupしたとき
// 選択しつつtext外でmouseupしたとき
// を拾えない
document.body.addEventListener('mouseup', () => {
const selection = window.getSelection()
if (selection.type === 'Range') {
// 選択領域の選択開始位置のNodeと選択終了位置のNodeを取得
const anchorNode = selection.anchorNode
const focusNode = selection.focusNode
// 選択開始位置と選択終了位置のNodeが同じでないと、タグで囲えない
if (anchorNode === focusNode) {
// markタグ内にmarkタグを作らないように、textの子を選択したときだけ
if (anchorNode.parentElement === text) {
const range = document.createRange()
// 後ろから前に選択したときは、無効なrangeになる。
// 今回は気にしない。必要であれば、anchorOffsetとfocusOffsetを入れ替えれば良い
range.setStart(anchorNode, selection.anchorOffset)
range.setEnd(anchorNode, selection.focusOffset)
const mark = document.createElement('mark')
range.surroundContents(mark)
}
}
}
})