I want to only allow selection from left to right, so the anchor node is always going to be the first node in the DOM tree (relative to the focus node).

Is there an easy way to test if the anchor node comes before the focus node?

有帮助吗?

解决方案

Here's a simple way to do it that 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. I think this will break in Firefox 2, which had a bug in its handling of this, but the number of users of that browser is tiny.

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;
}
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top