Selection ranges in webkit (Safari/Chrome)(webkit (Safari/Chrome) 中的选择范围)
问题描述
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!
Both 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.
这篇关于webkit (Safari/Chrome) 中的选择范围的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:webkit (Safari/Chrome) 中的选择范围
基础教程推荐
- 角度Apollo设置WatchQuery结果为可用变量 2022-01-01
- 悬停时滑动输入并停留几秒钟 2022-01-01
- 有没有办法使用OpenLayers更改OpenStreetMap中某些要素 2022-09-06
- Karma-Jasmine:如何正确监视 Modal? 2022-01-01
- 在for循环中使用setTimeout 2022-01-01
- 我什么时候应该在导入时使用方括号 2022-01-01
- 动态更新多个选择框 2022-01-01
- 在 JS 中获取客户端时区(不是 GMT 偏移量) 2022-01-01
- 响应更改 div 大小保持纵横比 2022-01-01
- 当用户滚动离开时如何暂停 youtube 嵌入 2022-01-01