How to select a node in a range with webkit browse

2019-01-28 10:49发布

问题:

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 clearly have a function for this w3.org/ranges and define that

range.selectNodeContents() // Select the contents within a node
and
range.selectNode() //Select a node and its contents

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)

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..

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 :/ )

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 : 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 :/

回答1:

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

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.