how to set multiple CSS style properties in typescript for an element?

前端 未结 4 1690
有刺的猬
有刺的猬 2021-02-12 20:09

Please consider the below snippet. i need to set multiple CSS properties in typescript. for that i have tried the below code.

public static setStyleAttribute(ele         


        
4条回答
  •  猫巷女王i
    2021-02-12 21:00

    The API you were searching for is: https://developer.mozilla.org/en-US/docs/Web/API/CSSStyleDeclaration/setProperty

    public static setStyleAttribute(element: HTMLElement, attrs: { [key: string]: Object }): void {
        if (attrs !== undefined) {
            Object.keys(attrs).forEach((key: string) => {
                element.style.setProperty(key, attrs[key]);
            });
        }
    }
    

    And hyphen is not allowed in object keys, so use ' here, too:

    let elem: HTMLElement = document.getElementById('myDiv');
    setStyleAttribute(elem, {'font-size':'12px', color: 'red', 'margin-top': '5px'});
    

提交回复
热议问题