使用javascript检测用户选择的方向 [英] Detect direction of user selection with javascript

查看:100
本文介绍了使用javascript检测用户选择的方向的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在我的项目中使用自定义插入符号模拟文本编辑器,但是本机选择。有没有办法如何检测用户选择文本的方向?可以说,该用户选择了文本hello world。有两种可能性,他可以从字母'd'上单击鼠标开始,以字母'h'结束,或者他可以从字母'h'开始,以字母'd'结束。有没有简单的方法来区分这两种情况?谢谢。

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 user has selected text "hello world". There are two possibilities, he could start with clicking his mouse on letter 'd' and ends on letter 'h', or he could start on letter 'h' and end on letter 'd'. Is there any easy way how to distinguish between these two situations? Thank you.

推荐答案

老问题,但我想我会添加一个更简单的解决方案:

Old question, but I thought I'd add an easier solution:

var sel = getSelection(),
position = sel.anchorNode.compareDocumentPosition(sel.focusNode),
backward = false;
// position == 0 if nodes are the same
if (!position && sel.anchorOffset > sel.focusOffset || 
  position === Node.DOCUMENT_POSITION_PRECEDING)
  backward = true; 

Node.compareDocumentPosition( MDN

Node.compareDocumentPosition (MDN)

这篇关于使用javascript检测用户选择的方向的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆