Selection.anchorOffset - 始点の位置
anchorOffsetは、Selectionのプロパティです。選択範囲の始点の位置を返します。
概要
- 名前
- anchorOffset
- 所属
- Selection
- IDL
readonly attribute unsigned long anchorOffset;
- 仕様書
- http://w3c.github.io/selection-api/#dom-selection-anchoroffset
説明
始点の位置を数値で返す。これは始点があるノード(anchorNode)の先頭から、始点の位置までのオフセット(文字数)を数値で表したものです。
選択を開始した位置が始点、終了した位置が終点です。選択範囲の右側と左側、どちらが始点、終点になるかは選択操作の方向で変わります。
デモ
Selection.anchorOffsetのデモです。例えば「い」だけを、左から右にかけて選択すると、始点は1("あ")、終点は2("あい")のオフセットになります。
<!-- このコードは編集できます。 -->
<!DOCTYPE html>
<head>
<style>
body { word-break: break-all ; }
div#result { white-space: pre-wrap ; }
</style>
</head>
<body>
<p>1234567890<br>あいうえおかきくけこ<br>abcdefghij<br>ABCDEFGHIJ</p>
<hr>
<div id="result"></div>
<script>
document.onselectionchange = function () {
document.getElementById( "result" ).textContent = "" ;
var selection = getSelection() ;
console.log( selection ) ;
appendText( selection + "\n\n" ) ;
appendText( "anchorNode: " + selection.anchorNode + " " + selection.anchorNode.data + "\n" ) ;
appendText( "anchorOffset: " + selection.anchorOffset + "\n" ) ;
appendText( "focusNode: " + selection.focusNode + " " + selection.focusNode.data + "\n" ) ;
appendText( "focusOffset: " + selection.focusOffset + "\n" ) ;
appendText( "isCollapsed: " + selection.isCollapsed + "\n" ) ;
appendText( "rangeCount: " + selection.rangeCount + "\n" ) ;
appendText( "type: " + selection.type + "\n" ) ;
}
function appendText ( text ) {
document.getElementById( "result" ).appendChild( document.createTextNode( text ) ) ;
}
</script>
</body>
</html>
サポート状況
Chrome | Firefox | Safari | Edge | IE | Opera | iOS Safari | Android |
---|---|---|---|---|---|---|---|
● | ● | ● | ● | ● 9+ | ● | ● | ● |
関連記事
- Document.getSelection()
- getSelection()は、Documentのメソッドです。選択中のテキストを表すSelectionを返します。
- Selection
- Selectionは、ユーザーが選択した範囲の情報を管理するための機能を備えたインターフェイスです。
- Selection.deleteFromDocument()
- deleteFromDocument()は、Selectionのメソッドです。選択範囲のコンテンツを削除します。
- Selection.removeAllRanges()
- removeAllRanges()は、Selectionのメソッドです。全ての選択範囲を解除します。