这是一个函数,它使用这样一个事实,即将 DOM 范围的结尾设置为文档中比范围开始更早的点会折叠范围。
演示:http: //jsfiddle.net/97MDR/17/
代码:
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;
}
}
return backwards;
}
它适用于所有主流浏览器,除了 IE < 9,它不支持与其他浏览器相同的 Range 和 Selection API。
对于 IE < 9,选择 API 中根本没有任何内容可以告诉您选择方向。我能建议的最好的方法是使用该selectionchange
事件来跟踪先前选择的范围,并查看每次触发时哪一端发生了变化。它似乎在以下示例中有效,但除此之外没有进行任何测试,因此使用风险自负。
演示:http: //jsfiddle.net/97MDR/18/
附加代码:
var selectedRange, selectionBackwards;
document.onselectionchange = function(evt) {
evt = evt || window.event;
var sel = document.selection;
if (sel && sel.type !== "Control") {
if (sel.type == "Text") {
// Selection is not collapsed, so compare range end points
var newRange = sel.createRange();
if (selectedRange) {
var startChanged = (newRange.compareEndPoints("StartToStart", selectedRange) != 0);
var endChanged = (newRange.compareEndPoints("EndToEnd", selectedRange) != 0);
if (startChanged && !endChanged) {
selectionBackwards = true;
} else if (endChanged && !startChanged) {
selectionBackwards = false;
} else if (startChanged && endChanged) {
// Both ends have changed, which is confusing.
// I suspect this can happen when the selection snaps
// to words. In this case we can tell nothing, so leave
// selectionBackwards alone.
} else {
// Neither end has changed, so we can tell nothing.
}
}
selectedRange = newRange;
} else {
// Selection is collapsed
selectionBackwards = false;
}
}
};