js获取html行内样式与外部样式、外联样式
1.//获取行内样式 这种方法只能够获取行内样式
var box=document.getElementById("box");
console.log(box.style.width);
2.获取外部样式以及外联样式
(1)除IE外可有使用的方法
//调用getComputedStyle就可以得到计算后的样式 即外部样式以及外联样式 但是只可以在除IE浏览器之外的浏览器使用
var cssObj=window.getComputedStyle(box);
console.log(cssObj.width);
(2)IE可以使用的方法
var cssObj = box.currentStyle;
console.log(cssObj.width);
//封装函数解决IE与其他浏览器方法不兼容的问题
function getCss(dom,attr){
//如果window.computedStyle这个方法存在 就可以调用这个方法
if(window.getComputedStyle){
//获取这个元素的所有样式组成的对象
var cssObj=window.getComputedStyle(dom);
//把要的属性返回出去
return cssObj[attr];
}else{
var cssObj=dom.currentStyle;
return cssObj[attr];
}
}