非行间样式就是写在style中的样式。要获取非行间样式根据浏览器划分,有两种方法。
//想要获取样式的元素
<div id="box" ></div>
//元素的样式
<style>
#box {
width: 200px;
height: 200px;
background: coral;
}
</style>
一:标准浏览器
比如:谷歌,狐火,360...
// getComputedStyle(元素).样式属性
getComputedStyle(box).height
二:IE
元素.currentStyle.样式属性
box.currentStyle.background
为了方便使用,可以封装成一个方法。
<script>
//通过id获得元素
var box = document.getElementById("box");
function fn(ele ,attr){
//判断是否是标准浏览器
if(window.getComputedStyle){
//是
// '.'没有办法识别变量,所有使用' [ ]'
return getComputedStyle(ele)[attr];
} else {
// 不是
return ele.currentStyle[attr];
}
}
//调用方法
fn(box,'width');
</script>