如何在contenteditable div中的每一行旁边显示行号

3
我有一个可编辑的div,并希望网站类似于许多编码IDE一样计算用户在div中拥有的每一行文本。(示例图像如下所示:)enter image description here 我该如何实现这个功能呢?

1
有很多种方法可以做到这一点。你尝试过什么?使用带有<li>元素的<ol>?表格?display:flex;display:grid; - StackSlave
2个回答

2
你可以通过两个容器元素和一点脚本来完成这个任务:

$(document).ready(function(){
  $('#edit').css('min-height', $('#edit').height());
  $('#edit').html('');
  var currentHeight = $('#edit').height();
  var lineHeight = currentHeight;
  $('#edit').keyup(function(){
    if($(this).height()!=currentHeight){
      currentHeight = $(this).height();
      var lines = currentHeight/lineHeight;
      $('#nums').html('')
      for (i = 1; i < lines+1; i++) {
        $('#nums').append('<span>'+i+'</span>')
      }
    }
  });
});
#container{
  border: 2px solid gray;
  display: flex;
  width: 200px;
}

#nums{
  width: 25px;
  background-color: lightgrey;
}

#nums span{
  width: 100%;
  display: block;
  text-align: center;
}

#edit{
  display: inline-block;
  width: 100%;
}

#editwrapper{
  width: 100%;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="container">
  <div id="nums">
    <span>1</span>
  </div>
  <div id="editwrapper">
    <div id="edit" contenteditable="true">
      filler
    </div>
  </div>
</div>


这段代码在stackoverflow的运行代码片段上似乎完美地工作了,但出于某种原因,我似乎无法让它在我的项目中正常工作。如果我尝试向contenteditable添加更多行,会出现更多的行,但只有第一行的编号实际上是可见的。 - Koto
@Koto 试着复现正在发生的事情。 - Libra
检查我的编辑在原帖中,以查看我迄今为止的进展。 - Koto
好的,没事了。我只是个笨蛋,没有正确设置我的脚本标签。谢谢! - Koto

-1

实际上这并不简单。如果用户在您的 div 中输入文本并进行了换行,JavaScript 并不知道它已经换行了;因为没有行可以计数!

这个解决方案非常具体化,我会让你自己显示行号:

<div contenteditable="true" id="myDiv" style="width:300px;font-family:monospace" onchange="myHandler()"></div>

<script>
const limit = 40 // number of monospace chars to fill a row
let count = 0
function myHandler (e) {
  let lines = Math.ceil(e.target.value.length / limit)
  if (lines !== count) {
    showlines(lines) // your function to display the line #s
    count = lines
  }
}
</script>

重点:您的 div 应该是固定宽度的,您应该计算在该宽度内有多少等宽字符适合。然后显示这些行。

你可以只使用相对于参考高度的方式,参见我的答案。 - Libra

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接