代码之家  ›  专栏  ›  技术社区  ›  POV

如何向HTML元素添加选择器?

  •  0
  • POV  · 技术社区  · 6 年前

    我有一个跨度元素:

    let infoButton = document.createElement("span"); 
    infoButton.setAttribute("class", "info-point");
    

    如何将选择器[bold]添加到元素中,以获得以下信息:

    <span [bold] class="info-point"></span>
    

    <span bold class="info-point"></span>
    
    3 回复  |  直到 6 年前
        1
  •  3
  •   Laminoo Lawrance    6 年前

    您可以使用以下指令来生成粗体文本。

    import { Directive, ElementRef } from '@angular/core';
    
    @Directive({
      selector: '[boldText]'
    })
    export class BoldTextDirective {
        constructor(el: ElementRef) {
           el.nativeElement.style.fontWeight = 'bold';
        }
    }
    

    HTML

    <span boldText class="info-point"></span>
    

    希望这有帮助。

        2
  •  2
  •   Sterling Archer    6 年前

    使用空字符串设置属性应该会得到这样的结果。这被称为布尔属性(常用于React、Angular等框架)。它们是有效的,定义见 W3 Specs .

    let infoButton = document.createElement("span"); 
    infoButton.setAttribute("class", "info-point");
    infoButton.setAttribute("bold", "");
    console.log(infoButton);
        3
  •  2
  •   Chris Love    6 年前

    最好使用本机API来管理元素类。

    var infoButton = document.createElement("span"); 
    
    infoButton.classList.add("info-point");