js原生获取css属性
原文参考http://blog.csdn.net/lzding/article/details/46317777
1.写在dom上的属性,内联样式
<div id="box" style="background-color:#ccc;margin-top:100px;"></div>
var oBox = document.getElementById('box')
console.log(oBox.style.width)
1)对于复合属性(如background),假设行间设置了样式:background-color:#333,不能通过 element.style.background 来获取(见上面例子)
2)css属性使用驼峰法,如 backgroundColor、marginTop等。
2.写在css中的属性,非内联样式(chrome)
var oBox = document.getElementById('box');
var a = getComputedStyle(oBox, null)['width']; // 100px
1)对于复合属性:使用 getPropertyValue 获取属性值时,不能使用驼峰写法,如:例子中的 getpropertyValue('backgroundColor') 无法正确获得值,而必须写成 background-color
2)另外,以下写法也正确:getComputedStyle(oBox, null)['backgroundColor']、getComputedStyle(oBox, null)['background-color'], 以及 getComputedStyle(oBox, null).backgroundColor 等
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】凌霞软件回馈社区,博客园 & 1Panel & Halo 联合会员上线
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】博客园社区专享云产品让利特惠,阿里云新客6.5折上折
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步