【问题标题】:Why Highlight.js doesn't work after redirect?为什么Highlight.js在重定向后不起作用?
【发布时间】:2020-04-18 19:51:25
【问题描述】:

我已经制作了一个迷你应用程序来描述这个问题,我正在尝试使用 highlight.js 来突出显示一些代码。问题是,当我从 site1 按下导航按钮时,它会将我导航到 site2,但突出显示不会应用,如果我从 site2 转到 site1,也会发生同样的事情,但是如果我在任何页面上刷新它都可以正常工作。

我需要使用导航,因为使用它我不会丢失变量的值。

testr.ts

import { Component, OnInit } from '@angular/core';
import { Router } from '@angular/router';
import hljs from 'highlight.js';

@Component({
  selector: 'app-testr',
  templateUrl: './testr.component.html',
  styleUrls: ['./testr.component.css']
})
export class TestrComponent implements OnInit {

  constructor(
    private router: Router
    ) {}

  ngOnInit() {
    hljs.initHighlightingOnLoad();
  }

  clickme(){
    this.router.navigate(['/teste']);
  }

}

testr.html

<p>testr works!</p>
<pre><code>var char; alert(1+1)</code></pre>
<button (click)="clickme()" value="Link">Link</button>

teste.ts

import { Component, OnInit } from '@angular/core';
import hljs from 'highlight.js';
import { Router } from '@angular/router';

@Component({
  selector: 'app-teste',
  templateUrl: './teste.component.html',
  styleUrls: ['./teste.component.css']
})
export class TesteComponent implements OnInit {

  constructor(
    private router: Router
  ) { }

  ngOnInit() {
    hljs.initHighlighting();
  }

  clickme(){
    this.router.navigate(['/testr']);
  }
}

teste.html

<p>teste works!</p>
<pre><code>var char; alert(1+1)</code></pre>
<button (click)="clickme()" value="Link">Link</button>

【问题讨论】:

    标签: angular typescript syntax-highlighting highlight highlight.js


    【解决方案1】:

    Highlight.js 无法突出显示“onload”事件触发时不存在的代码。我猜实际上只有您的第一个视图存在(当页面加载时),而您的第二个视图仅在您“访问”第二个页面时添加到实际的 DOM 中。

    切换页面后,您需要手动调用initHighlighting 以突出显示现在已添加到页面的任何新代码块。

    【讨论】:

      猜你喜欢
      • 2019-09-14
      • 2016-09-13
      • 1970-01-01
      • 2021-10-31
      • 2011-08-21
      • 1970-01-01
      • 1970-01-01
      • 2017-06-12
      • 2017-04-02
      相关资源
      最近更新 更多