如何知道文本区域中当前可见哪些行/字符?

发布于 2024-12-03 17:25:13 字数 571 浏览 2 评论 0原文

具有“实时预览”功能的在线编辑器:左侧有一个文本区域,右侧有一个预览 div。每当文本区域发生变化时,预览都会更新。

这对于小文档非常有效;然而,对于很长的文档,它会变得缓慢,因为预览中有大量不断重新绘制的 DOM 元素。

最好只发送到预览,当前可见的文本区域部分(因为它是需要预览的部分)。

有一种启发式方法可以获取文本区域的第一条可见行:

  1. 确定文本区域的当前滚动偏移量:
    偏移量=滚动顶部/滚动高度
    (0 < offset < 1)
  2. 文本区域中可见的第一行是:
    (总行数)x 偏移量

但是,这仅适用于“短”行,即不换行的行。一般来说,文本区域中的“行”数不是换行符的数量;没有换行符的长行会换行并可能占用许多“行空间”。

人们可以尝试计算一行占用的“行间距”的平均数量(换行符之间的平均字符数、文本区域的宽度、字体的大小......),但这非常不精确。

有没有办法知道文本区域中第一个和最后一个可见字符的位置?

Online editor with "live preview": there is a textarea on the left and a preview div on the right. Whenever the textarea changes, the preview is updated.

This works well for small documents; for very long documents however, it becomes sluggish, because the preview has lots of DOM elements that are constantly repainted.

It would be better to only send to the preview, the part of the textarea that is currently visible (since it's the one that needs to be previewed).

There is a heuristic way to get the first visible line of the textarea:

  1. determine current scroll offset of the textarea:
    offset = scrollTop / scrollHeight
    (0 < offset < 1)
  2. the first line that is visible in the textarea is:
    (total number of lines) x offset

However this only works for "short" lines, ie lines that don't wrap. In general, the number of "lines" in a textarea is not the number of linebreaks; a long line, without linebreaks, wraps and might occupy many "line spaces".

One could try to calculate the average number of "line spaces" a line occupies (average number of characters between line breaks, width of textarea, size of font...) but this is wildly imprecise.

Is there a way to know the position of the first and last visible characters in a textarea?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

信愁 2024-12-10 17:25:13

好吧,作为一种疯狂的方法,您可以看看 ACE 如何将文本转换为画布绘制的线条。我假设通过这种方法,您可以确定确切的位置(或者更好地说,当前可见的确切 line 对象。

但是,如果画布生成的文本是 。

或者,您可以使用固定宽度的字体,这将使您了解单行中的确切字符数,从而计算出准确的第一行/最后一行 。

Well, as a crazy way for doing it you can look how ACE converts the text into canvas-drawn lines. I assume with this approach you can determine the exact position (or better to say, the exact line objects that are currently visible.

But this could also be a kind of vicious circle if the canvas-generated text is compatible in complexity to what you are having in the preview.

Alternatively you can use a fixed-width font which will give you a knowledge of the exact number of chars in the single line, and thus a way of calculating the exact first / last lines.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文