借鉴了鑫神的博客,关于动态的获取style
jquery的话 直接 通过 .css('属性') 这样的方法就能获取
如果通过原生态的javascript话
测试环境 IE11 ,FireFox 52.0 ,Chrome 56.0
兼容写法
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<style>
div{
width:300px;
height: 300px;
background:green;
border-bottom: 1px solid black;
}
</style>
</head>
<body>
<div>1111111</div>
</body>
<script>
//以下方法 兼容 IE11 chrome firefox
var div=document.getElementsByTagName("div")[0];
//必须采用驼峰式命名
console.log(getComputedStyle(div)['borderBottomWidth']);
//getPropertyValue使用了非驼峰式命名
console.log(getComputedStyle(div).getPropertyValue("border-bottom-width"));
</script>
</html>
这里用到了 getComputedStyle这个方法 注意 获取属性的 驼峰式和非驼峰式的区别
俗话说的好,自古“IE”奇葩多,IE下还能这样写,仅仅只能在IE下
console.log(div.currentStyle['borderBottomWidth']);
好了web发展到现在难免还有一些老用户(IE8,IE9),最终给出一个兼容写法
function getStyle(object,attr){
return object.currentStyle?object.currentStyle[attr]:getComputedStyle(object)[attr];
}
大功告成,之前一直习惯了 jquery的css()方法,今天研究了一番做下笔记