扫码一下
查看教程更方便
在 typescript 中为元素设置 css 样式:
el.style.backgroundcolor = 'lime'
。这是本文中示例的 html。
hello 迹忆客(jiyik.com)
这是相关的 typescript 代码。
// 常量 box: htmlelement | null
const box = document.getelementbyid('box');
if (box != null) {
box.style.backgroundcolor = 'lime';
box.style.color = 'white';
box.style.fontsize = '2em';
}
我们使用 document.getelementbyid
方法来选择元素。 如果 dom 中不存在具有提供的 id 的元素,则该方法返回 null,因此我们必须确保 box 变量在访问其上的任何属性之前不存储 null 值。
如果我们需要从元素中删除特定的 css 属性,请将其设置为空字符串。
如果我们改用 document.getelementsbyclassname
方法,请将元素键入为 html 元素的集合。
const boxes = array.from(
document.getelementsbyclassname('box') as htmlcollectionof,
);
boxes.foreach(box => {
box.style.backgroundcolor = 'lime';
box.style.color = 'white';
box.style.fontsize = '2em';
});
getelementsbyclassname
方法返回 htmlcollectionof
类型,并且 element 接口不包含 style 属性。
这就是我们使用类型断言将集合键入为 htmlcollectionof
的原因。
我们使用样式对象来设置元素的 css 属性。
注意
,在使用样式对象时,多词属性名称是驼峰式大小写的。
如果你不喜欢 css 属性名是驼峰式的,你可以使用 setproperty
方法。
// 常量 box: htmlelement | null
const box = document.getelementbyid('box');
if (box != null) {
box.style.setproperty('background-color', 'lime');
box.style.setproperty('color', 'white');
}
setproperty 方法采用以下 3 个参数:
我们还可以使用样式对象从元素中读取 css 属性值。
// 常量 box: htmlelement | null
const box = document.getelementbyid('box');
if (box != null) {
box.style.setproperty('background-color', 'lime');
// "lime"
console.log(box.style.backgroundcolor);
// "16px"
console.log(window.getcomputedstyle(box).fontsize);
}
第一个示例读取元素的背景颜色属性值。
但是,如果该属性未设置为元素的内联样式,这将不起作用。
如果我们需要考虑在外部样式表中设置样式,请改用
window.getcomputedstyle
方法。
getcomputedstyle
方法在应用样式表后返回一个对象,该对象包含传入元素的所有 css 属性的值。