IInline Comment Complex
by bisque
HTML
<p id="row">装飾されたテキストの<span class="selection">選択範囲</span>を取得する</p>
<div id="result"></div>
CSS
.selection {
background-color: rgba(255, 128, 0, 0.4);
}
JavaScript
document.addEventListener("mouseup", () => {
const selection = window.getSelection();
if (selection.isCollapsed) return;
// テキスト全体のNode
const rowElm = document.getElementById("row")
const anchorOffset = selection.anchorOffset;
const focusOffset = selection.focusOffset;
let startOffset = 0; // テキスト全体のオフセット
let endOffset = 0; // テキスト全体のオフセット
let anchorNode = selection.anchorNode;
let focusNode = selection.focusNode;
// SPANに囲まれたTEXT_NODEなら、そのparentNodeをanchorNodeとする
if (anchorNode.nodeType === Node.TEXT_NODE && anchorNode.parentNode.nodeName === "SPAN") {
anchorNode = anchorNode.parentNode;
}
if (focusNode.nodeType === Node.TEXT_NODE && focusNode.parentNode.nodeName === "SPAN") {
focusNode = selection.focusNode.parentNode;
}
// anchorNodeは選択を開始した地点なので、文章の上部とは限らない
// anchorNodeとfocusNodeの前後比較してstartNode, endNodeを設定する
const anchorIndex = Array.from(rowElm.childNodes).indexOf(anchorNode);
const focusIndex = Array.from(rowElm.childNodes).indexOf(focusNode);
// anchorIndexとfocusIndexが同じ場合
if (anchorIndex === focusIndex) {
// rowElmのNodeを先頭から走査し、Offsetを求める
Array.from(rowElm.childNodes).forEach((node, i) => {
if (i < anchorIndex) {
startOffset += node.textContent.length;
endOffset += node.textContent.length;
}
if (i === anchorIndex) {
startOffset += Math.min(selection.anchorOffset, selection.focusOffset);
endOffset += Math.max(selection.anchorOffset, selection.focusOffset);
}
});
} else {
const isAnchorFirst = anchorIndex < focusIndex;
const startNodeIndex = isAnchorFirst ? anchorIndex : focusIndex;
const endNodeIndex = isAnchorFirst ? focusIndex : anchorIndex;
// rowElmのNodeを先頭から走査し、Offsetを求める
Array.from(rowElm.childNodes).forEach((childNode, i) => {
if (i < startNodeIndex) {
startOffset += childNode.textContent.length;
}
if (i === startNodeIndex) {
startOffset += isAnchorFirst ?...