如何使用 webkit 浏览器选择范围内的节点?

2022-01-24 00:00:00 webkit range javascript contenteditable

我目前正在研究 WYSIWYG 解决方案,需要一个函数来正确选择一个节点的范围(我指的是节点本身,而不仅仅是它的内容)

I'm currently working on a WYSIWYG solution and need a function to correctly select with a range a node (by this I mean the node itself, not only it's content)

DOM lvl2 显然有这个功能 w3.org/ranges 并定义

DOM lvl2 clearly have a function for this w3.org/ranges and define that

range.selectNodeContents()//选择节点内的内容

range.selectNode()//选择一个节点及其内容

问题是,当 selectNode() 完美地与 Firefox 甚至 ie9 一起工作时,似乎不可能用任何 Webkit 浏览器(最后是 Chrome 和 Safari)来实现.在 Webkit 上 selectNodeContents() 和 selectNode() 都只选择节点内容(根据规范,这在我看来是一个错误)

The problem is that when selectNode() perfectly work with Firefox or even ie9, it seem to be impossible to achieve with any Webkit browser (at last Chrome and Safari). On Webkit both selectNodeContents() and selectNode() select the node content only (which according to the specs seems to me to be a bug)

为了使它工作,我尝试通过使用来模拟 selectNode() 目标
range.setStartBefore(node);
range.setEndAfter(节点);

但结果还是一样,它可以在任何地方工作(当然是>8),但不能在 webkit 浏览器上工作..

To make it work I tried to emulate the selectNode() goal by using
range.setStartBefore(node);
range.setEndAfter(node);

but the result is still the same, it work everywhere (ie>8 of course) but not on webkit browsers..

如果你想试试,我做了一个小 jsfiddle,你可以用它玩 here(只是打开控制台并查看console.warn结果,这在webkit上是不一样的:/)

If you want to try it I made a little jsfiddle with which you can play here (just open the console and look at the console.warn result which is not the same on webkit :/ )

我搜索了很多,但找不到在 webkit 浏览器上实际选择完整节点的方法.奇迹般地,你们中的一些人会知道一种方法来做到这一点,或者甚至只是任何提示来继续我的探索吗?:/

I searched a lot but I can't find a way to actually select a full node on webkit browsers. By miracle would some of you know a way to do it or even just any tip to continue my quest ? :/

ps:我知道rangy"库,但我不能在我的项目中使用它,而且从我在源代码中读到的内容来看,我什至不确定他们是否处理那个东西:/

ps : I know "rangy" lib but I can't use it in my project and ,from what I read in the source, I'm not even sure they deal with that thing anyway :/

推荐答案

问题不在于 selectNode(),它在 WebKit 中运行良好,而在于 WebKit 的选择对象,它会破坏范围以适应在允许选择边界和插入符号位置的位置有自己的(并非总是不合理的)想法.WebKit 对此有一些错误:

The problem is not with selectNode(), which works fine in WebKit, but with WebKit's selection object, which mangles ranges to fit in with its own (not always unreasonable) idea of where selection boundaries and caret positions are allowed to be. There are bugs filed against this with WebKit:

  • https://bugs.webkit.org/show_bug.cgi?id=23189
  • https://bugs.webkit.org/show_bug.cgi?id=15256

你说得对,Rangy 并没有处理这个问题,而是更愿意反映浏览器原生选择的现实.假装选择不同会很快导致奇怪的行为.

You're right, Rangy does not deal with this, preferring instead to reflect the reality of the browser's native selection. Pretending the selection is different would quickly lead to odd behaviour.

相关文章