使用 TypeScript 在元素上设置 CSS 样式

您所在的位置:网站首页 typescript操作dom 使用 TypeScript 在元素上设置 CSS 样式

使用 TypeScript 在元素上设置 CSS 样式

#使用 TypeScript 在元素上设置 CSS 样式| 来源: 网络整理| 查看: 265

在 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 个参数:

propertyName - 我们要修改的 CSS 属性的名称。 请注意,多个单词的属性名称必须连字符。 value - CSS 属性的新值。 priority - 可以设置为重要或空字符串。

我们还可以使用样式对象从元素中读取 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 属性的值。



【本文地址】


今日新闻


推荐新闻


CopyRight 2018-2019 办公设备维修网 版权所有 豫ICP备15022753号-3