【问题标题】:CodeMirror Line-Break doesn't add line number - AngularCodeMirror Line-Break 不添加行号 - Angular
【发布时间】:2020-07-20 11:58:55
【问题描述】:

我正在使用来自 ngx-codemirror 的代码镜像。我想在适合父级宽度时分割线。我找到了一些解决方案来拆分类似使用,

lineWrapping: true

风格

.CodeMirror-wrap pre {
  word-break: break-word;
}

使用它我可以拆分行,但我也需要显示行号。 刚刚拆分的行不显示行号。 这是我的问题的 stackblitz 链接:code-mirror-line-break-issue

截图:

请帮帮我。

【问题讨论】:

  • 这在我看来是正常行为,但您希望同一行号显示两次或更多是拆分行吗?
  • 我没有完全得到你的要求。您能否附上一些反映您期望的屏幕截图?
  • @David 实际上,即使该行被拆分,我也需要每行(连续)的行号。你能检查一下更新的截图和stackblitz链接吗
  • @yurzui 我附上了截图。您能否检查一下以及 stackblitz 链接?每行应连续显示行号
  • 好的,我现在明白了,但这有点违反直觉。假设两个人在电话/网络聊天中讨论一段代码/json。如果他们有不同的窗口/屏幕尺寸,当一个人向另一个人提及行号时,他们不会看到相同的东西

标签: css angular typescript codemirror ngx-codemirror


【解决方案1】:

使用代码镜像选项这是不可行的,因为这有点违反直觉,很少(曾经?)想要。

就像我在评论中所说的那样,假设 2 个人在电话/网络聊天中讨论一段代码/json。如果他们有不同的窗口/屏幕尺寸,当一个人向另一个人提及行号时,他们不会看到相同的东西

解决方案

作为一种技巧,您可以创建自己的元素来表示行号并将它们放置在默认行号之上。

这里是stackblitz demo

注意:这是一个非常基本的示例。如果您更改代码镜像设置(字体大小、间距等),您可能需要调整 css 或根据这些设置进行更多计算。

component.html

<div class='codeMirrorContainer'>
  <ngx-codemirror
      #codeMirror
      [options]="codeMirrorOptions"
      [(ngModel)]="codeObj"
    ></ngx-codemirror>

<ul class='lineContainer' [style.top.px]="-topPosition">
  <li [style.width.px]='lineWidth' *ngFor="let line of lines">{{line}}</li>
</ul>
</div>

component.css

li
{
  height: 19px;
  list-style: none;
}

.codeMirrorContainer
{
  position:relative;
  overflow: hidden;
}

.lineContainer
{
  position:absolute;
  top:0;
  left:0;
  margin: 0;
    padding: 5px 0 0 0;
  text-align: center;
  
}

::ng-deep .CodeMirror-linenumber
{
  visibility: hidden; /* Hides default line numbers */
}

component.ts

export class AppComponent
{


  @ViewChild('codeMirror') codeMirrorCmpt: CodemirrorComponent;

  private lineHeight: number;
  public lineWidth;

  public topPosition: number;
  public lines = [];

  codeMirrorOptions: any = ....;
  codeObj :any = ...;

  constructor(private cdr: ChangeDetectorRef)
  {
  }



  ngAfterViewInit()
  {
    this.codeMirrorCmpt.codeMirror.on('refresh', () => this.refreshLines());
    this.codeMirrorCmpt.codeMirror.on('scroll', () => this.refreshLines());
    setTimeout(() => this.refreshLines(), 500)

  }


  refreshLines()
  {
    let editor = this.codeMirrorCmpt.codeMirror;
    let height = editor.doc.height;
    this.lineHeight = editor.display.cachedTextHeight ? editor.display.cachedTextHeight : this.lineHeight;
    if (!this.lineHeight)
    {
      return;
    }
    let nbLines = Math.round(height / this.lineHeight);
    this.lines = Array(nbLines).fill(0).map((v, idx) => idx + 1);
    this.lineWidth = editor.display.lineNumWidth;
    this.topPosition = document.querySelector('.CodeMirror-scroll').scrollTop;
    this.cdr.detectChanges();

  }


}

【讨论】:

  • 这有点棘手,但它确实有帮助!感谢您的解决方案。
  • 欢迎。是的,这很棘手,但您要求的并不常见
猜你喜欢
  • 2015-07-13
  • 2013-09-23
  • 1970-01-01
  • 1970-01-01
  • 2016-01-07
  • 2022-12-01
  • 2021-07-14
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多