Webkit中的选择范围

Webkit中的选择范围

本文介绍了Webkit中的选择范围(Safari/Chrome)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用内容可编辑的iframe在javascript中创建语法高亮显示,最重要的事情之一就是能够正确缩进代码.

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.

以下代码在Firefox中的工作原理与之相同:

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);

它将创建一个制表符,并将光标移动到字符的右侧.在Chrome和Safari中,插入了一个字符,但光标不会移到它的右侧.

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.

我检查了Chrome和Firefox中的范围对象,然后发现Firefox的范围对象比Chrome的范围对象丰富得多.我一直无法在webkit中找到范围对象的任何规格.

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.

如何使此代码同时适用于webkit和Firefox?

How can I make this code work for both webkit and Firefox?

谢谢!

推荐答案

Firefox和WebKit的Range对象完全符合 DOM范围规范.如果Firefox具有更多属性,则它们将是Mozilla自己的扩展,但是通常该规范提供了您可能需要的一切.

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);

请注意,这在Safari的早期版本(我认为是版本3之前)中不起作用,因为其选择对象不支持 getRangeAt .如果您需要,我可以提供一种解决方法.

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)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-26 10:50