我正在尝试使用 getBoundingClientRect() 在 contenteditable div 中获取光标的 y 坐标。代码的 IE 分支工作,但另一个分支(即 Firefox 3.5 用于我当前的测试目的)不工作。
下面的代码在注释中有问题的行用 *** 标记。在代码中,selObj 和 selRange 都有一个值(在 Firebug 中确认),但我不能在其中任何一个上调用 getBoundingClientRect() (例如,selObj.getBoundingClientRect 不是一个函数)。我已经读到 getBoundingClientRect() 现在在 Firefox 上支持 Range 对象,但我无法让它工作。我想我一定是在错误类型的对象上调用它......?我应该怎么称呼它?
以下代码是包含相关 javascript 的 html 文件的完整测试用例。在 IE 中查看,我得到了光标 y 坐标的值,但在 Firefox 中它会弹出。
<html>
<head>
<title>Test</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<style>
#pageContainer {
padding:50px;
}
.pageCommon {
width: 100px;
height: 100px;
background-color:#ffffD0;
padding: 10px;
border: 1px solid black;
overflow: auto;
}
</style>
</head>
<body>
<div id="pageContainer">
<div id="editor" class="pageCommon" contenteditable onclick="setPageNav();" onkeypress="setPageNav();">
</div>
<div>y: <span id="y"></span></div>
</div>
<script>
var y;
function setPageNav() {
page = document.getElementById("editor");
if (window.getSelection) {
var selObj = window.getSelection();
var selRange = selObj.getRangeAt(0);
// *** Neither of these next two lines work, error is : selObj.getBoundingClientRect is not a function
y = selObj.getBoundingClientRect().top;
y = selRange.getBoundingClientRect().top;
} else if (document.selection) {
var range = document.selection.createRange();
y = range.getBoundingClientRect().top;
}
document.getElementById("y").innerHTML = y;
}
</script>
</body>
</html>