Sri*_*jan 10 css typescript tslint
请考虑以下代码段.我需要在typescript中设置多个CSS属性.为此,我尝试了以下代码.
public static setStyleAttribute(element: HTMLElement, attrs: { [key: string]: Object }): void {
if (attrs !== undefined) {
Object.keys(attrs).forEach((key: string) => {
element.style[key] = attrs[key];
});
}
}
Run Code Online (Sandbox Code Playgroud)
对于上面的代码,我需要传递参数为
let elem: HTMLElement = document.getElementById('myDiv');
setStyleAttribute(elem, {font-size:'12px', color : 'red' , margin-top: '5px'});
Run Code Online (Sandbox Code Playgroud)
但是上面的代码抛出错误(tslint),因为Element隐式具有'any'类型,因为索引表达式不是'number'类型.(属性)HTMLElement.style:CSSStyleDeclaration.
请帮我 !!!
the*_*ide 26
尝试使用setAttribute.TypeScript没有该style属性Element.
element.setAttribute("style", "color:red; border: 1px solid blue;");
Run Code Online (Sandbox Code Playgroud)
此GitHub问题中的一些相关讨论:https: //github.com/Microsoft/TypeScript/issues/3263
我希望这可以帮助您或其他人...
您可以使用 aHTLMDivElement和其中CSSStyleDeclaration包含的来实现这一点。例如。
var container: HTMLDivElement;
container.style.color = "red";
container.style.fontSize = "12px";
container.style.marginTop = "5px";
Run Code Online (Sandbox Code Playgroud)
这也适用于继承自HTMLElement并具有style属性的其他类(例如HTMLBodyElement.
您正在搜索的 API 是: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]);
});
}
}
Run Code Online (Sandbox Code Playgroud)
对象键中不允许使用连字符,因此也请在此处使用 ':
let elem: HTMLElement = document.getElementById('myDiv');
setStyleAttribute(elem, {'font-size':'12px', color: 'red', 'margin-top': '5px'});
Run Code Online (Sandbox Code Playgroud)
派对晚了一点,但是无论如何...
实际的问题不是上style没有定义Element。这个词Element在开始时Element implicitly has an 'any' type because index expression is not of type 'number'. (property) HTMLElement.style: CSSStyleDeclaration只是一个句子的第一个字,因此大写。意味着它与Element对象没有任何关系-这很令人困惑。
但是,错误消息表示您正尝试使用下标运算符访问[]索引类型错误的属性。在您的情况下,您key的类型是,string但是它HTMLElement.style是一个CSSStyleDeclaration具有的索引签名的对象,[index: number]: string因此要求您的密钥是type number。
索引签名来自typescript/lib/lib.dom.d.tsTypeScript安装中的声明文件。在那里你会发现CSSStyleDeclaration。
因此,您可以做的只是简单地any像这样:
(<any>element.style)[key] = attr[key];
Run Code Online (Sandbox Code Playgroud)
这不是最好的解决方案,但它有效且简单。它还不需要您像使用时那样将样式化element.setAttribute。