【问题标题】:getBoundingClientRect problem with FirefoxFirefox 的 getBoundingClientRect 问题
【发布时间】:2011-01-15 17:52:54
【问题描述】:

我正在尝试使用 getBoundingClientRect() 在内容可编辑的 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>

【问题讨论】:

  • “流行音乐”?你能解释一下这是什么意思吗?它会抛出异常吗?
  • 是的,对不起,这就是我所说的“流行音乐”的意思

标签: javascript firefox contenteditable


【解决方案1】:

我已经读到 getBoundingClientRect() 现在在 Firefox 上支持 Range 对象

还没有。这是 Mozilla 1.9.3 的一项功能,您可以在 Firefox 3.7 中期待。

无论如何你都需要后备,因为任何其他浏览器都不支持它。

【讨论】:

  • MDC 声称它在 FF 3 及更高版本中:developer.mozilla.org/En/DOM/Element.getBoundingClientRect 刚刚检查过,它在 FF 3.6、Chrome 和 Safari 中显示为一个函数。我不知道它在各种实现中的一致性如何。
  • 这就是Element 方法。新功能为 Range 添加了相同的功能。
  • getBoundingClientRect()getClientRects() 现在得到了更好的支持:Firefox 4、WebKit 自 2009 年初以来以及 Opera 从……某个时候开始。
【解决方案2】:

我已经读到,getBoundingClientRect() 现在在 Firefox 上支持 Range 对象

The support for that is new in Gecko 1.9.3 alpha,在 3.6.x 之后的 Firefox 版本中将包含此功能。 Firefox 3.5 不支持。

【讨论】:

  • 根据 MDC,它在 Firefox 3 及更高版本中:developer.mozilla.org/En/DOM/Element.getBoundingClientRect 甚至还有一个关于 FF 3.5 中的实现的特别说明
  • @T.J. Crowder:“它”是 Element.getBoundingClientRect。请注意,它不同于 Range.getBoundingClientRect,它是 Gecko 1.9.3 中的新功能,正如我和发行说明所说的那样。
猜你喜欢
  • 2016-05-25
  • 2021-02-27
  • 2011-02-17
  • 2016-09-16
  • 2011-03-04
  • 2010-12-05
  • 2011-08-31
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多