【问题标题】:Semantics of clientRect from getClientRects in webkit browserswebkit 浏览器中来自 getClientRects 的 clientRect 语义
【发布时间】:2011-11-06 03:48:15
【问题描述】:

在 webkit 浏览器中(这在 IE9 或 Mozilla 中似乎不是问题)当查询 clientRects (getClientRects) 的范围时,返回的 clientrects 包含与所选文本相对应的文本矩形,但也包含 clientrects范围内任何元素的开始。我如何确定哪些 clientrects 属于元素。

例如,假设这个段落是用我在这里的相同换行符呈现的:

<p>This is some text StartSelection in a paragraph 
    blah blah<span>this is some EndOfSelection blah
    more text</span>
</p>

如果我从 StartSelection 选择到 EndOfSelection,然后从选择中查询范围 - getRangeAt(0)

我会取回这个 clientRects 数组:

0. rect of 'StartSelection in a paragraph'
1. rect of 'blah blah'
2. rect of 'this is some EndOfSelection blah'
3. rect of 'more text'
4. rect of 'this is some EndOfSelection'

我想要的唯一矩形是 0、1 和 4。矩形 2 和 3 表示选择跨越的元素的开始标记的内容。

矩形的几何检查可以让我放弃 2 和 3,但代码让我觉得有点脆弱,特别是如果我的选择要扩展到第三行。有没有办法在没有几何检查的情况下确定矩形的来源,我可以用它来丢弃 2 和 3?

【问题讨论】:

  • 出于好奇,您想通过getClientRects() 实现什么目标?
  • 我正在尝试突出显示文本,与文本选择分开。如果我可以在选择中注入多个范围,我可以接受,但这似乎支持有限。
  • 为什么不遍历 Range 的 DOM 或使用 document.execCommand()(例如:stackoverflow.com/questions/6972581/…)?
  • 谢谢我没有看到那个答案,很好的优雅解决方案,但是我不想因为其他原因改变内容。因此,我将使用 rects 指示高光的单独平面/装饰(上方、下方)的路线。
  • 嗯。我看到了问题。我会向 WebKit 提交一个错误并尝试找到解决方法。

标签: javascript selection range


【解决方案1】:

据我所知没有。 Range 的这个特性在所有浏览器中都是相对较新的,我很少看到关于它的文章,所以我认为它没有被广泛使用并且很可能存在浏览器错误。例如,这似乎是一个 WebKit 错误,因为在我看来,它违反了the part of the CSSOM View spec pertaining to Ranges。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-04-06
    • 2013-04-27
    • 1970-01-01
    • 1970-01-01
    • 2012-06-03
    • 1970-01-01
    • 2016-10-11
    相关资源
    最近更新 更多