我正在尝试使用 getBoundingClientRect() 获取 contenteditable div 中光标的 y 坐标。代码的 IE 分支可以工作,但另一个分支(即用于我当前测试目的的 Firefox 3.5)则不能。
下面的代码在注释中用 *** 标记了有问题的行。在代码中的这一点上, selObj 和 selRange 都有一个值(在 Firebug 中确认),但我无法在它们中的任何一个上调用 getBoundingClientRect() (例如 selObj.getBoundingClientRect 不是一个函数)。我读到, Firefox 现在支持 Range 对象上的 getBoundingClientRect() ,但我无法让它工作。我想我一定是在错误类型的对象上调用它......?我应该用什么来称呼它?
以下代码是完整的测试用例,作为包含相关 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>
我读到 Firefox 现在支持 Range 对象上的 getBoundingClientRect()
还没有,还不是。这是 Firefox 3.7 中可以期待的 Mozilla 1.9.3 功能。
无论如何,您都需要后备,因为任何其他浏览器都不支持它。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)