我们有时候会需要在 JS 中对文档元素的 style 进行获取和更改,这篇文章将简要的讨论一下和 style 相关的内容。
前端设置 style 样式有三种方式:
<p style="color: red;" > Hello </p>
<head>
<style>
....
</style>
</head>
<link rel="stylesheet" href="path/style.css" type="text/css">
我们通过 element.style 来获取内联样式。注意:此方法无法获取内置和外联样式。
可以直接通过 style 来操作属性:
// 获取属性
console.log(ele.style.color)
// 删除属性
ele.style.color = ''
// 更新属性
ele.style.color = 'blue'
应为通过 style 属性获取的样式只包含了内联样式,不包含内置和外联样式,所以如果想要获取一个元素最终的样式内容,就需要使用 window.getComputedStyle。
例如,想要获取一个元素的 border 属性可以这么写:
window.getComputedStyle(ele).border
style 和 getComputedStyle 的区别:
1. style 只能获取内联样式,getComputedStyle 能够获取完整样式。
2. style 可以读和写,但是 getComputedStyle 是只读的。可以通过读取 getComputedStyle 的内容来修改 style。
cssText 是 style 属性中可读可写的一个属性,它会返回该元素所有的内联样式。并且如果你修改了 cssText,会覆盖之前的内联样式。
ele.style = "width: 100px; height: 100px; color: red;"
ele.style.cssText = "color: green;"
console.log(ele.style.cssText) // color: green;
可以看到上面的代码中,因为修改了 cssText,元素的内联样式被完全覆盖了。
原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。
如有侵权,请联系 cloudcommunity@tencent.com 删除。
原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。
如有侵权,请联系 cloudcommunity@tencent.com 删除。