admin管理员组文章数量:1201584
I'm using a content-editable iframe to create a syntax-highlighter in javascript and one of the most important things is to be able to indent code properly.
The following code works just as it should in Firefox:
// Create one indent character
var range = window.getSelection().getRangeAt(0);
var newTextNode = document.createTextNode(Language.tabChar);
range.insertNode(newTextNode);
range.setStartAfter(newTextNode);
It creates a tab char and moves the cursor to the right side of the character. In Chrome and Safari a character is inserted but the cursor won't move to the right of it.
I inspected the range object in both Chrome and Firefox, and then noticed that Firefox's range object is far richer than Chrome's. I have been unable ro find any specs of the range object in webkit.
How can I make this code work for both webkit and Firefox?
Thank you!
I'm using a content-editable iframe to create a syntax-highlighter in javascript and one of the most important things is to be able to indent code properly.
The following code works just as it should in Firefox:
// Create one indent character
var range = window.getSelection().getRangeAt(0);
var newTextNode = document.createTextNode(Language.tabChar);
range.insertNode(newTextNode);
range.setStartAfter(newTextNode);
It creates a tab char and moves the cursor to the right side of the character. In Chrome and Safari a character is inserted but the cursor won't move to the right of it.
I inspected the range object in both Chrome and Firefox, and then noticed that Firefox's range object is far richer than Chrome's. I have been unable ro find any specs of the range object in webkit.
How can I make this code work for both webkit and Firefox?
Thank you!
Share Improve this question asked Feb 6, 2010 at 17:30 ChristofferChristoffer 26.8k18 gold badges54 silver badges77 bronze badges1 Answer
Reset to default 23Both Firefox and WebKit's Range objects comply fully with the DOM Range spec. If Firefox has more properties then they will be Mozilla's own extensions, but generally the spec provides everything you could need.
Anyway, the problem is that you need to reselect the range after altering it:
// Create one indent character
var sel = window.getSelection();
var range = sel.getRangeAt(0);
var newTextNode = document.createTextNode(Language.tabChar);
range.insertNode(newTextNode);
range.setStartAfter(newTextNode);
sel.removeAllRanges();
sel.addRange(range);
Note that this will not work in early versions of Safari (prior to version 3, I think), because its selection object does not support getRangeAt
. There is a workaround for this I can provide if you need it.
本文标签: javascriptSelection ranges in webkit (SafariChrome)Stack Overflow
版权声明:本文标题:javascript - Selection ranges in webkit (SafariChrome) - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1738615830a2102901.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论