gpt4 book ai didi

internet-explorer - 在 IE 中选择 StartContainer

转载 作者:行者123 更新时间:2023-12-04 12:56:31 26 4
gpt4 key购买 nike

我有一个选择对象,在 IE 中,我运行

range = selection.createRange();

然后我尝试获取 startContainer 但我无法弄清楚如何。所有示例都向我展示了设置 startContainer,但我基于突出显示文本。我如何知道将它设置为哪个元素而不先获取它?

我知道在 FireFox 中它很简单
range     = selection.getRangeAt(0);
firstNode = range.startContainer;

最佳答案

【已经两年了。】
好的,这会很丑,但我想我得到了这个问题的答案(似乎适用于 IE8)。代码如下(解释在注释中):

/**
* @param {window object} win The window from which the selection is to be retrieved. This could also be an iframe.contentWindow.
*/
function getRangeObject(win) { //Gets the first range object.
win=win || window;
if (win.getSelection) { // W3C/FF/Chrome/Safari/Opera/IE9
return win.getSelection().getRangeAt(0); //W3C DOM Range Object
}
else if(win.document.selection) { // IE8
return win.document.selection.createRange(); //Microsoft TextRange Object
}
return null;
}

function getStartContainer(win) {
win=win || window;
var range=getRangeObject(win);
if(range) {
if(range.startContainer) { // W3C/FF/Chrome/Safari/Opera/IE9
return range.startContainer;
} else if(document.selection) { //IE8
var rangeCopy=range.duplicate(); //Create a copy
var rangeObj=range.duplicate();

rangeCopy.collapse(true); //Go to beginning of the selection
rangeCopy.moveEnd('character',1); //Select only the first character
//Debug Message
//alert(rangeCopy.text); //Should be the first character of the selection
var parentElement=rangeCopy.parentElement();
rangeObj.moveToElementText(parentElement); //Select all text of parentElement
rangeObj.setEndPoint('EndToEnd',rangeCopy); //Set end point to the first character of the 'real' selection
var text=rangeObj.text; //Now we get all text from parentElement's first character upto the real selection's first character

//Iterate through all the child text nodes and check for matches
//As we go through each text node keep removing the text value (substring) from the beginning of the text variable.
var container=null;
for(var node=parentElement.firstChild; node; node=node.nextSibling) {
if(node.nodeType==3) {//Text node
var find=node.nodeValue;
var pos=text.indexOf(find);
if(pos==0 && text!=find) { //text==find is a special case
text=text.substring(find.length);
} else {
container=node;
break;
}
}
}
range.startContainer=container; //Finally we are here
//Debug Message
//alert(container.nodeValue);
}
}
}

抱歉评论过多(我认为这是必要的)。一旦你删除所有这些评论,你就会得到代码......不那么难看:P。

关于internet-explorer - 在 IE 中选择 StartContainer,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1223324/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com