Created
June 28, 2016 10:12
-
-
Save cmilfont/728236db8e23b4046e249425c2f12502 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
getTextNodesIn = (node) => { | |
var textNodes = []; | |
if (node.nodeType == 3) { | |
textNodes.push(node); | |
} else { | |
var children = node.childNodes; | |
for (var i = 0, len = children.length; i < len; ++i) { | |
textNodes.push.apply(textNodes, this.getTextNodesIn(children[i])); | |
} | |
} | |
return textNodes; | |
} | |
setSelectionRange = (el, start, end) => { | |
if (document.createRange && window.getSelection) { | |
var range = document.createRange(); | |
range.selectNodeContents(el); | |
var textNodes = this.getTextNodesIn(el); | |
var foundStart = false; | |
var charCount = 0, endCharCount; | |
for (var i = 0, textNode; textNode = textNodes[i++]; ) { | |
endCharCount = charCount + textNode.length; | |
if (!foundStart && start >= charCount | |
&& (start < endCharCount || | |
(start == endCharCount && i <= textNodes.length))) { | |
range.setStart(textNode, start - charCount); | |
foundStart = true; | |
} | |
if (foundStart && end <= endCharCount) { | |
range.setEnd(textNode, end - charCount); | |
break; | |
} | |
charCount = endCharCount; | |
} | |
var sel = window.getSelection(); | |
sel.removeAllRanges(); | |
sel.addRange(range); | |
} else if (document.selection && document.body.createTextRange) { | |
var textRange = document.body.createTextRange(); | |
textRange.moveToElementText(el); | |
textRange.collapse(true); | |
textRange.moveEnd("character", end); | |
textRange.moveStart("character", start); | |
textRange.select(); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Hi,
can you share some logic to get all child nodes and creating range of highlight text on web ?
scenario: when user select some text and do highlight on web , I want to validate that text range and elment rect
objHighlightOverlay.clientWidth and rangItem.width