Skip to content

Instantly share code, notes, and snippets.

@sainu
Last active November 25, 2017 04:21
Show Gist options
  • Save sainu/ad8a8f939eaca2ac0d208351da41e85c to your computer and use it in GitHub Desktop.
Save sainu/ad8a8f939eaca2ac0d208351da41e85c to your computer and use it in GitHub Desktop.
HTMLを含んだcontenteditable内のカーソル位置取得

HTMLを含んだcontenteditable内のカーソル位置取得 DEMO

Select something in the content below:
<div id="editor" contenteditable="true">A <i>wombat</i> is a marsupial native to <b>Australia</b>
<p>test</p>
</div>
<div id="selectionLog"></div>
function getSelectionCharacterOffsetWithin(element) {
var start = 0;
var end = 0;
var doc = element.ownerDocument || element.document;
var win = doc.defaultView || doc.parentWindow;
var sel;
if (typeof win.getSelection != "undefined") {
sel = win.getSelection();
if (sel.rangeCount > 0) {
var range = win.getSelection().getRangeAt(0);
var preCaretRange = range.cloneRange();
preCaretRange.selectNodeContents(element);
preCaretRange.setEnd(range.startContainer, range.startOffset);
console.log(range.startOffset);
start = preCaretRange.toString().length;
preCaretRange.setEnd(range.endContainer, range.endOffset);
end = preCaretRange.toString().length;
}
} else if ( (sel = doc.selection) && sel.type != "Control") {
var textRange = sel.createRange();
var preCaretTextRange = doc.body.createTextRange();
preCaretTextRange.moveToElementText(element);
preCaretTextRange.setEndPoint("EndToStart", textRange);
start = preCaretTextRange.text.length;
preCaretTextRange.setEndPoint("EndToEnd", textRange);
end = preCaretTextRange.text.length;
}
return { start: start, end: end };
}
function reportSelection() {
var selOffsets = getSelectionCharacterOffsetWithin( document.getElementById("editor") );
document.getElementById("selectionLog").innerHTML = "Selection offsets: " + selOffsets.start + ", " + selOffsets.end;
}
window.onload = function() {
document.addEventListener("selectionchange", reportSelection, false);
document.addEventListener("mouseup", reportSelection, false);
document.addEventListener("mousedown", reportSelection, false);
document.addEventListener("keyup", reportSelection, false);
};
#editor {
background-color: #eee;
padding: 1rem;
}
#editor[contenteditable=true]:empty:before {
content: attr(placeholder);
color: #999;
display: block; /* For Firefox */
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment