开发者

Internet Explorer equivalent range.startOffset

How can I get functionality equivalent to that of range.startOffset in Internet Explorer 8 and below?

I.e., I'd like a function I can call on a range that will tell me how man开发者_StackOverflow社区y characters into its container the range starts.


If you want a DOM Range implementation in IE, you could use my Rangy library: http://code.google.com/p/rangy/.

var range = rangy.getSelection().getRangeAt(0);
alert(range.startOffset);


Here an example-code, see the comments inside:

<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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜