【问题标题】:Show html color from a string显示字符串中的 html 颜色
【发布时间】:2020-10-23 02:57:06
【问题描述】:

我有一个字符串,在变量“prod.de.description”中,它是一个对象的描述,就像这样:

"<p><strong>Test</strong></p><p><strong><span style="background-color: #ed7e32;">Test2</span></strong></p>"

当我使用 innerhtml 时,它只显示强而不是背景颜色。这是html代码和结果:

 <div class="col-10" style="padding-left:0; font-size:0.9rem">
    <div class="row">
      <div class="col-3 text-right">
        <label class="modal-tag">DESCRIPTION</label>
      </div>
      <div class="col-9">
        <p [innerHTML]="prod.de.description"></p>
      </div>
    </div>

这就是我现在得到的:

为什么我在 Test2 下没有得到背景颜色,而只有强? 我是 HTML 的新手。非常感谢!

【问题讨论】:

  • 尝试将单引号放在双引号中。或者反之亦然。喜欢"&lt;p&gt;&lt;strong&gt;Test&lt;/strong&gt;&lt;/p&gt;&lt;p&gt;&lt;strong&gt;&lt;span style='background-color: #ed7e32;'&gt;Test2&lt;/span&gt;&lt;/strong&gt;&lt;/p&gt;"
  • 你必须以某种方式处理文字双引号,要么用单引号替换字符串中的双引号,要么将字符串换成单引号

标签: html css angular frontend backend


【解决方案1】:

您在字符串内部和外部使用相同的引号 (")。 这可能会导致问题。使用不同的。也许是这样的:

"<p><strong>Test</strong></p><p><strong><span style='background-color: #ed7e32;'>Test2</span></strong></p>"

【讨论】:

    【解决方案2】:

    您正在使用框架的innerHTML 指令,它会在放入您的dom 之前清理内容。它将删除样式标签和脚本作为安全问题。局外人可以用他们的内容进行攻击。为了防止这种情况,框架会做这件事。

    但是,当您知道您正在从 trusted sources 放置内容时,框架也会让位于逃避这种情况。

    点击此链接:

    https://stackblitz.com/edit/angular-8-app-example-mzdwkd

    import { Component } from '@angular/core';
    import { DomSanitizer } from '@angular/platform-browser';
    
    @Component({
      selector: 'my-app',
      templateUrl: './app.component.html',
      styleUrls: [ './app.component.css' ],
    })
    
    export class AppComponent  {
    
      description = '<p><strong>Test</strong></p><p><span style="background-color: #ed7e32;">Test2</span></p>';
    
      constructor(private sanitizer: DomSanitizer){}
    
       transformYourHtml(htmlTextWithStyle) {
           return this.sanitizer.bypassSecurityTrustHtml(htmlTextWithStyle);
       }
      }
    

    HTML:

    &lt;p [innerHTML]="transformYourHtml(description)"&gt;&lt;/p&gt;

    【讨论】:

    • 试过了,还是不行……真的不知道怎么解决。
    • @RobNone 嗨对不起,我了解到您没有使用任何框架。我以为您使用的是纯 innerHTML 标签。但是,您使用的是框架 [innerHTML] 指令,它会在放入 dom 进行安全检查之前检查内容。我已经更新了我的答案
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-12-14
    • 1970-01-01
    • 2015-03-07
    • 2020-07-30
    • 2019-02-09
    • 1970-01-01
    • 2017-11-07
    相关资源
    最近更新 更多