2011-01-26 79 views
1

如何在Internet Explorer 8及更低版本中獲得與range.startOffset相同的功能?Internet Explorer等效range.startOffset

也就是說,我想要一個函數,我可以調用一個範圍來告訴我範圍開始的容器中有多少個字符。

+0

`range.startOffset`是僅相對於其直接容器的偏移量,並且僅當容器是文本節點時纔是字符偏移量。那是你要的嗎? – 2011-01-27 00:18:45

+0

@Tim:你是對的;這不是我想要的。我創建了一個新的問題:http://stackoverflow.com/questions/4811822/get-a-ranges-start-and-end-offsets-relative-to-its-parent-container – 2011-01-27 00:36:47

回答

1

下面的示例代碼,看到裏面的意見:如果你想在IE中的DOM範圍實現,你可以用我的四肢修長庫

<html> 
<head> 
<title>Test</title> 
<script type="text/javascript"> 
<!-- 
function fx() 
{ 
    //create a range of selection 
    var rng = document.selection.createRange(); 
    //if nothing is selected return null 
    if(rng.text=='')return null; 
    //create a second range of selection 
    var rng2 = document.selection.createRange(); 
    //let the 2nd range encompass the whole element 
    rng2.moveToElementText(rng.parentElement()) 
    //move the end-point of the 2nd range to the start-point of the 1st range 
    rng2.setEndPoint('EndToStart', rng); 
    //return the length of the text in the 2nd range 
    return(rng2.text.length); 
} 
//--> 
</script> 
</head> 
<body> 
<input type="button" onclick="alert(fx())" value="select some text below and then click me"> 
<p>1234<b style="color:red">5678</i>90</p> 
</body> 
</html> 
+0

這不完全等同於Range的` startOffset`,它僅與其直接的容器節點相關。然而,這可能是OP想要的,這在其他瀏覽器中很難實現。 – 2011-01-27 00:15:00