Detect direction of user selection with javascript

后端 未结 5 991
没有蜡笔的小新
没有蜡笔的小新 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:09

    This should work:

    function isBackwards(sel) {
      var rg = document.createRange();
      rg.setStart(sel.anchorNode, sel.anchorOffset);
      rg.setEnd(sel.focusNode, sel.focusOffset);
      return !rg.toString();
    }
    

    Note: If you allow selections of nothing but breaks and whitespace you need to modify above function since it would return true in such a case, no matter what.

提交回复
热议问题