DOM:确定anchorNode或focusNode是否在左侧 [英] DOM: determine if the anchorNode or focusNode is on the left side

查看:555
本文介绍了DOM:确定anchorNode或focusNode是否在左侧的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

此方法...

window.getSelection().anchorNode

...告诉我们文本STARTS的选择。

...tells us where the selection of text STARTS.

此方法...

window.getSelection().focusNode

...告诉我们选择文本ENDS。

...tells us where the selection of text ENDS.

由于文本可以选择从左到右向左,这不是INFER, anchorNode 位于 focusNode 的左侧。

Since text can be selecting dragging left-to-right or right-to-left this does not INFER that the anchorNode is to the left of the focusNode.

可以使用什么DOM / JavaScript方法确定哪个引用节点在文本选择的左侧?

What DOM/JavaScript method can be used to determine which referenced node is on the LEFT side of the text selection?

澄清:这是为了修复 startContainer()方法的错误( window.getSelection()。getRangeAt(0).startContainer ),因此这是一个无效的建议。

Clarification: this is to fix the bug for the startContainer() method (window.getSelection().getRangeAt(0).startContainer) and thus that is an invalid suggestion.

推荐答案

你通常会使用 anchorNode 和 focusNode 之间的rel =nofollow> Node.compareDocumentPosition() 是道德的等价物 DOCUMENT_POSITION_PRECEDING (除非你有一个RTL文本当然)。我假设你真的想知道哪个是文档中的第一个,而不是屏幕上的位置。这样的事情将会起作用:

You would usually use Node.compareDocumentPosition() on anchorNode and focusNode, "left" is the moral equivalent of DOCUMENT_POSITION_PRECEDING (unless you have an RTL text of course). I assume that you actually want to know which comes first in the document and not the position on screen. Something like this will work:

let selection = window.getSelection();
let position = selection.anchorNode.compareDocumentPosition(selection.focusNode);
if (position & Node.DOCUMENT_POSITION_FOLLOWING)
  alert("Left-to-right selection");
else if (position & Node.DOCUMENT_POSITION_PRECEDING)
  alert("Right-to-left selection");
else
  alert("Only one node selected");

这篇关于DOM:确定anchorNode或focusNode是否在左侧的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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