简体   繁体   English

在 javascript IE8 中设置选择范围

[英]Set selection range in javascript IE8

I'm working on a wysiwyg editor using div[contenteditable=true] and I want to set a selection range from offset X of Node A to offset Y of Node B. I did it well on Firefox and IE9, the code is :我正在使用 div[contenteditable=true] 使用所见即所得编辑器,我想设置从节点 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);

But on IE8, the range object is totally different, it has no setStart/setEnd, and the selection object has no remove/addRange stuffs.但是在 IE8 上,range 对象完全不同,它没有 setStart/setEnd,并且选择对象没有 remove/addRange 的东西。 Please help,请帮忙,

Take a look at rangy.看看 rangy。 Its a cross browser range/selection API.它是一个跨浏览器范围/选择 API。 That's probably what you need.这可能就是你所需要的。

http://code.google.com/p/rangy/ http://code.google.com/p/rangy/

I had a similar problem found this polyfill which was quite useful to me, as I could not use rangy in my situation: http://bl.ocks.org/visnup/3456262我有一个类似的问题,发现这个 polyfill 对我非常有用,因为在我的情况下我不能使用 rangy: http : //bl.ocks.org/visnup/3456262

Edit: original link has indeed gone dead.编辑:原始链接确实已经死了。 Looking back over my old code it looks like the polyfill never made it into the release code, we simply went with feature detection as follows:回顾我的旧代码,看起来 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)

...and the IE8 users are therefore not supported for that feature. ...因此该功能不支持 IE8 用户。

However all is not lost: there's a newer (than my original answer) polyfill on Github which might work if you have to support IE8.然而,一切都没有丢失: Github 上有一个更新的(比我原来的答案)polyfill,如果您必须支持 IE8,它可能会起作用。 It looks both pretty lean and comprehensive.它看起来既简洁又全面。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM