如何在Internet Explorer 8及更低版本中获得与range.startOffset
相同的功能?
即,我想要一个函数,我可以在一个范围内调用,它会告诉我容器中有多少个字符开始。
答案 0 :(得分:5)
如果你想在IE中实现DOM Range,你可以使用我的Rangy库:http://code.google.com/p/rangy/。
var range = rangy.getSelection().getRangeAt(0);
alert(range.startOffset);
答案 1 :(得分: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>