admin管理员组文章数量:1290080
This method...
window.getSelection().anchorNode
...tells us where the selection of text STARTS.
This method...
window.getSelection().focusNode
...tells us where the selection of text ENDS.
Since text can be selecting dragging left-to-right or right-to-left this does not INFER that the anchorNode
is to the left of the focusNode
.
What DOM/JavaScript method can be used to determine which referenced node is on the LEFT side of the text selection?
Clarification: this is to fix the bug for the startContainer()
method (window.getSelection().getRangeAt(0).startContainer
) and thus that is an invalid suggestion.
This method...
window.getSelection().anchorNode
...tells us where the selection of text STARTS.
This method...
window.getSelection().focusNode
...tells us where the selection of text ENDS.
Since text can be selecting dragging left-to-right or right-to-left this does not INFER that the anchorNode
is to the left of the focusNode
.
What DOM/JavaScript method can be used to determine which referenced node is on the LEFT side of the text selection?
Clarification: this is to fix the bug for the startContainer()
method (window.getSelection().getRangeAt(0).startContainer
) and thus that is an invalid suggestion.
- stackoverflow./questions/7486509/… – Andreas Commented May 22, 2012 at 22:04
2 Answers
Reset to default 9You would usually use Node.pareDocumentPosition() on anchorNode
and focusNode
, "left" is the moral equivalent of DOCUMENT_POSITION_PRECEDING
(unless you have an RTL text of course). I assume that you actually want to know which es first in the document and not the position on screen. Something like this will work:
let selection = window.getSelection();
let position = selection.anchorNode.pareDocumentPosition(selection.focusNode);
if (position & Node.DOCUMENT_POSITION_FOLLOWING)
alert("Left-to-right selection");
else if (position & Node.DOCUMENT_POSITION_PRECEDING)
alert("Right-to-left selection");
else
alert("Only one node selected");
A method I've used for this uses the fact that setting the end of a DOM Range to be at an earlier point in the document than the start of the range will collapse the range:
function isSelectionBackwards() {
var backwards = false;
if (window.getSelection) {
var sel = window.getSelection();
if (!sel.isCollapsed) {
var range = document.createRange();
range.setStart(sel.anchorNode, sel.anchorOffset);
range.setEnd(sel.focusNode, sel.focusOffset);
backwards = range.collapsed;
range.detach();
}
}
return backwards;
}
本文标签: javascriptDOM determine if the anchorNode or focusNode is on the left sideStack Overflow
版权声明:本文标题:javascript - DOM: determine if the anchorNode or focusNode is on the left side - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1741489997a2381575.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论