Bold
Hello World!
This is bold
ddd
show code
まず、document.getSelection()でselectionオブジェクトを取得する。
let selection=document.getSelection ();
selectionは複数の可能性がある。selectionの数を知るには、selection.rangeCountを使用する。
selection.rangeCount
selectionのrangeCount が0以上の場合は、rangeを取得できる。
以下の例では最初のrangeを取得する。
if(selection.rangeCount>0){
const range=selection.getRangeAt(0);
実際のところ、もしselectionが存在するなら、rangeCountは常に1である。
1以上はNetscapeでしか起きない。
the Selection API was initially
created by Netscape and allowed multiple ranges
(for instance, to allow the user to select a column
from a <table>). However, browsers other than
Gecko did not implement multiple ranges, and
the specification also requires the selection
to always have a single range.
単にカーソルがエリア内に置かれているだけでも、rangeがあるといえる。
この場合、rangeはcollapsedしていると表現できる。
この場合、range.collapsed はtrueになる。
rangeには、range.startContainer とrange.endContainer がある。
以下のように、selectionの初めと終わりが違うNodeに属する場合、
range.startContainer <> range.endContainer である。
Hello <b>Wo rld<b>
commonAncestorContainer は、range.startContainerとrange.endContainerが
共有するparentのNodeである。
rangeがContentEditableの内部であるためには、range.startContainerと
range.endContainerがcontainsされていなければいけない。
el_editor.contains(range.startContainer) &&
el_editor.contains(range.endContainer)