如何知道textarea中当前可见的行

如何知道textarea中当前可见的行

本文介绍了如何知道textarea中当前可见的行/字符?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述 29岁程序员,3月因学历无情被辞! 带有实时预览的在线编辑器:左侧有一个textarea,右侧有一个预览div。每当textarea更改时,预览都会更新。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.这适用于小型文档;然而,对于很长的文档,它变得迟钝,因为预览有很多不断重新绘制的DOM元素。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.最好只发送到预览,当前可见的textarea的一部分(因为它是需要预览的部分)。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).有一种启发式方法来获取textarea的第一个可见行:There is a heuristic way to get the first visible line of the textarea: 确定textarea的当前滚动偏移量: offset = scrollTop / scrollHeight (0< offset< 1) 在textarea中可见的第一行是: (总数线条)x偏移determine current scroll offset of the textarea:offset = scrollTop / scrollHeight(0 < offset < 1)the first line that is visible in the textarea is:(total number of lines) x offset然而,这仅适用于短线,即不包裹的线。一般来说,textarea中行的数量不是换行符的数量;一条长线,没有换行符,包裹并且可能占据许多行间距。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".可以尝试计算一条线占据的行间距的平均数量(平均值)换行符之间的字符数,textarea的宽度,字体的大小...)但这是非常不精确的。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. 有没有办法知道这个位置textarea中的第一个和最后一个可见字符?推荐答案嗯,作为一种疯狂的方式你做到了可以看看 ACE 如何将文本转换为画布绘制的线条。我假设使用这种方法你可以确定准确的位置(或更好的说,当前可见的确切行对象。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. 这篇关于如何知道textarea中当前可见的行/字符?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持! 上岸,阿里云!
08-30 06:44