javascript 获取元素样式常用方法。
Javascript获取CSS属性值方法:getComputedStyle和currentStyle
1 .对于元素的内联CSS样式(<div style="color:#369">hello</div>),可以直接使用element.style.color来直接获取css属性的值;
2. 但是对于外部定义的css样式使用这种方式就无法获取了,而且IE浏览器和其他标准浏览器(Firefox,Chrome,Opera,Safari)使用的方法不一样,IE浏览器使用element.currentStyle,W3C标准浏览器使用getComputedStyle来获取。
1. IE获取元素外部定义的CSS属性值: element.currentStyle
currentStyle对象返回了元素上的样式表,但是style对象只返回通过style标签属性应用到元素的内嵌样式。
因此,通过currentStyle对象获取的样式值可能与通过style对象获取的样式值不同。
例如,如果段落的color属性值通过链接或嵌入样式表设置为红色( red ),而不是内嵌的话,对象.currentStyle.color 将返回正确的颜色,而对象style.color不能返回值。但是,如果用户指定了 <P STYLE="color:'red'">,currentStyle和STYLE对象都将返回值 red。
currentStyle对象反映了样式表中的样式优先顺序。
在 HTML 中此顺序为:
1) 内嵌样式
2) 样式表规则
3) HTML 标签属性
4) HTML 标签的内部定义
2. W3C获取元素外部定义的CSS属性值: window.getComputedStyle(element, pseudoElt)
element必选,HTML元素
pseudoElt必选,获取该元素的伪类样式
function getStyle(node, property){
if (node.style[property]) {
return node.style[property];
}
else if (node.currentStyle) {
return node.currentStyle[property];
} // www.jbxue.com
else if (document.defaultView && document.defaultView.getComputedStyle) {
var style = document.defaultView.getComputedStyle(node, null);
return style.getPropertyValue(property);
}
return null;
}
if (node.style[property]) {
return node.style[property];
}
else if (node.currentStyle) {
return node.currentStyle[property];
} // www.jbxue.com
else if (document.defaultView && document.defaultView.getComputedStyle) {
var style = document.defaultView.getComputedStyle(node, null);
return style.getPropertyValue(property);
}
return null;
}
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义
· 地球OL攻略 —— 某应届生求职总结
· 提示词工程——AI应用必不可少的技术
· Open-Sora 2.0 重磅开源!
· 周边上新:园子的第一款马克杯温暖上架