Detect direction of user selection with javascript

后端 未结 5 1081
没有蜡笔的小新
没有蜡笔的小新 2020-12-30 05:43

I am emulating text editor in my project with custom caret, but native selection. Is there any way how to detect in which direction did user select the text? Lets say, that

5条回答
  •  佛祖请我去吃肉
    2020-12-30 06:27

    I was trying to find a solution that works for me for a couple of days. Here is what I came up with, this will work with single range selection:

    var selection = window.getSelection();
    var range = selection.getRangeAt(0);
    var isSelectionDown = selection.focusNode === range.endContainer;
    var isSelectionUp = selection.focusNode === range.startContainer;
    

    The focus node of selection is always where the user releases the mouse, but the range end and start containers change depending on direction.

提交回复
热议问题