亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

從 JavaScript 插入 DOM 元素時,不顯示 CSS 樣式

從 JavaScript 插入 DOM 元素時,不顯示 CSS 樣式

青春有我 2023-11-12 14:24:27
我想顯示帶有標題和內容的日志。使用以下代碼,li將元素插入到右側的 DOM 中className,但不顯示樣式。這是在 Angular 組件內部,我認為這可能是錯誤的根源。這只是一個帶有 html 的基本新應用程序:<app-example></app-example>注意:如果我在 html 中手動插入一個元素,它會正確顯示。我注意到的唯一區別是li從 javascript 插入的元素沒有_ngcontent-cxr-c40.網頁:<ul class="d-flex f-column log-list" id="log-list">        <li id="log-item" class="log-message">          <span class="log-message-title">TEST</span>        </li></ul>這是向日志添加元素的函數:  private addLogElement(title: string, message: string): void {    const newNode = document.createElement('li');    newNode.className = 'log-message';    const newNodeTitle = document.createElement('span');    newNodeTitle.className = 'log-message-title';    const headerText = document.createTextNode(title);    newNodeTitle.appendChild(headerText);    newNode.appendChild(newNodeTitle);    const parentDiv = document.getElementById('log-list');    const childDiv = document.getElementById('log-item');    parentDiv.insertBefore(newNode, childDiv);  }
查看完整描述

2 回答

?
慕哥6287543

TA貢獻1831條經驗 獲得超10個贊

您應該使用 Renderer2 API 進行此類 DOM 操作。


在構造函數的 Component 類中注入它,如下所示:-


constructor(public renderer: Renderer2) {}

然后將您的方法更改為:-


private addLogElement(title: string, message: string): void {

    const newNode = this.renderer.createElement('li');

    this.renderer.addClass(newNode, 'log-message');

    const newNodeTitle = this.renderer.createElement('span');

    this.renderer.addClass(newNodeTitle, 'log-message-title');

    const headerText = this.renderer.createText(title);

    this.renderer.appendChild(newNodeTitle, headerText);

    this.renderer.appendChild(newNode, newNodeTitle);


    const parentDiv = this.renderer.selectRootElement(document.getElementById('log-list'), true);

    const childDiv = this.renderer.selectRootElement(document.getElementById('log-item'), true);

    this.renderer.insertBefore(parentDiv, newNode, childDiv);

  }

您應該使用 Renderer2 而不是本機 DOM 操作還有其他原因。


您可以在此處參考這些原因:- https://medium.com/dev-genius/dont-use-native-dom-manipulations-in-angular-6c8db13f463f


查看完整回答
反對 回復 2023-11-12
?
30秒到達戰場

TA貢獻1828條經驗 獲得超6個贊

將其添加到您的css/scss

我已添加示例樣式中


:host ::ng-deep .log-message{

    color: red;

}

:host ::ng-deep .log-message-title{

    background-color: #eeee33

}


查看完整回答
反對 回復 2023-11-12
  • 2 回答
  • 0 關注
  • 258 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號