我正在使用div[contenteditable=true]制作wysiwyg编辑器我想设置一个选择范围,从节点a的偏移量X到节点b的偏移量Y。我在Firefox和IE9上做得很好,代码是:
var range = document.createRange();
range.setStart(selectNode, 0);
range.setEnd(selectNode, selectNode.textContent.length);
var sel = window.getSelection();
sel.removeAllRanges();
sel.addRange(range);
但是在IE8上,范围对象是完全不同的,它没有setStart/setEnd,并且选择对象没有remove/adrange之类的东西。请帮助,
看一下rangy。它是一个跨浏览器范围/选择的API。这可能就是你需要的。
http://code.google.com/p/rangy/我有一个类似的问题,发现这个填充对我很有用,因为我不能在我的情况下使用range:http://bl.ocks.org/visnup/3456262
编辑:原来的链接确实已经死了。回顾我的旧代码,看起来polyfill从未进入发布代码,我们只是按照如下方式进行特征检测:
if(window.getSelection || document.selection){
then on mouseup:
var range;
if(window.getSelection){
var selection = window.getSelection();
range = selection.getRangeAt(0);
} else if(document.selection){
range = document.selection.createRange();
if(!range.surroundContents){
// then give up, feature not fully implemented
}
}
// now do stuff with range (i.e. the selection)
…因此,IE8用户不支持该功能。
然而,一切都没有失去:有一个更新的(比我原来的答案)polyfill在Github上可能工作,如果你必须支持IE8。它看起来既简洁又全面。