1

如何获得与range.startOffsetInternet Explorer 8 及更低版本中的功能等效的功能?

即,我想要一个可以在范围上调用的函数,该函数将告诉我该范围开始在其容器中的字符数。

4

2 回答 2

5

如果你想在 IE 中实现 DOM Range,你可以使用我的 Rangy 库:http ://code.google.com/p/rangy/ 。

var range = rangy.getSelection().getRangeAt(0);
alert(range.startOffset);
于 2011-01-27T00:16:53.757 回答
1

这是一个示例代码,请参阅里面的注释:

<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>
于 2011-01-26T23:59:21.547 回答