Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
419 views
in Technique[技术] by (71.8m points)

javascript - How to select a node in a range with webkit browsers?

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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:

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...