【问题标题】:Add a class to div with dynamic value [duplicate]将类添加到具有动态值的 div [重复]
【发布时间】:2020-01-08 14:41:04
【问题描述】:

我想用 ts 中生成的动态值向我的一个 div 添加一个类。

假设我有以下代码来添加一个类:

let item = document.querySelector('.my-div');
item.classList.add('max-width');

let myMaxWidthValue = '200'; // this value is going to be generated by some fn

现在我想以某种方式使类在 css 中看起来像这样:

.max-width .innerItems {
  max-width: myMaxWidthValue
}

这可能吗?我这样做会更有效率。

从我的 CSS 可以看出,我想将类设置为包含许多子元素的父类。

我可以使用getElementsByClassName 并使用element[0].style.maxWidth = myMaxWidthValue 循环遍历每个元素,但是这些子元素可能有很多,而且这样做似乎不正确。

【问题讨论】:

标签: html css angular typescript


【解决方案1】:

您可以为此使用Renderer2

constructor(private renderer2: Renderer2) {

}

ngOnInit() {
    let styles = document.createElement('style');
    let maxWidthValue = '200px';

    let css = `.max-width .innerItems {
      max-width: ${maxWidthValue};
    }`;

    this.styles.type = 'text/css';
    this.styles.appendChild(document.createTextNode(css));
    this.renderer2.appendChild(document.body, styles);
}

使用 jquery,您可以简单地做到这一点:

$(document).ready(function () {
      $("#idOfStyleElement").append('your css');
});

【讨论】:

    猜你喜欢
    • 2017-04-02
    • 2017-10-23
    • 1970-01-01
    • 2015-01-09
    • 1970-01-01
    • 2021-01-03
    • 2011-05-16
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多