【问题标题】:JQuery line numbers on Textarea with wrapping support带有包装支持的 Textarea 上的 JQuery 行号
【发布时间】:2015-10-17 10:53:02
【问题描述】:

我正在处理带有行号的文本区域。现在我发现了一个很棒的小脚本。 http://jakiestfu.github.io/Behave.js/

在这里演示:http://jakiestfu.github.io/Behave.js/examples/example-hook-linenums.html

我缺少的一项功能是启用换行的能力。

当然,我可以将 wrap="on" 添加到 textarea,这确实提供了换行,但是行号随后被弄乱了。

知道如何添加对换行的支持以保持行号正确吗?

【问题讨论】:

  • 您是否意识到 BehaveHooks.add(['keydown'], function(data){ 从未被调用过?
  • 行号在这里从 CSS 的角度来看是混乱的。为 textarea 尝试 'float:right' 和 'float:left;宽度:20px;位置:相对;'对于 div.line-nums
  • 恐怕不会产生预期的效果。当换行打开时,在 1 行中输入的文本多于 textarea 中的文本,文本将在下面继续,但它会立即在第一行的第二部分的位置添加另一个行号,即您按 Enter 键的那一刻。示例:i.imgur.com/wMONnF2.png 真的只有 2 行
  • 我第二条评论中的 CSS 仅适用于左侧的灰色行号框。你的主要问题(我认为)是,这个 keydownFunction 永远不会被调用。 (至少在我的 Firefox 中)

标签: javascript jquery textarea


【解决方案1】:

试试这个:

<!DOCTYPE html>
<html>
<body onload="keyDown()">

<div class="container" style="width:300px;">
    <div id="numbers" style="float:left; background:gray; width:20px;"></div>
    <textarea onkeypress="keyDown()" rows="1" style="line-height:20px; display:block; float:right; overflow:hidden;" id="ta"></textarea>
</div>


<script type="text/javascript"> 
    function keyDown(){         
        var taLineHeight = 20; // This should match the line-height in the CSS
        var taHeight = ta.scrollHeight; // Get the scroll height of the textarea
        ta.style.height = taHeight + "px"; // This line is optional, I included it so you can more easily count the lines in an expanded textarea
        var numberOfLines = Math.floor(taHeight/taLineHeight);
        var inner= "";
        for(var i=1; i<=numberOfLines; i++)
            inner += "<div>"+i+"</div>";
        document.getElementById("numbers").innerHTML = inner;           
    }       
</script>

</body></html>

【讨论】:

  • 你好,谢谢你,但这不会产生结果,我担心 :( jsfiddle.net/hs5pnsnd 我也希望它与 Behave.js 一起工作。该函数被调用(至少在 chrome 中),只是脚本的制作方式,它不支持我需要的包装。
猜你喜欢
  • 2018-03-16
  • 2020-06-29
  • 2018-12-12
  • 2016-11-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多