1.计算样式
<style>
#app{
font-size:40px;
width: 200px;
height: 200px;
background-color: green;
}
</style>
<div id="app" style="color: red;">
hello
</div>
2.获取元素
//app.style属性只能获取行内样式,不能获取css中的样式
console.log(app.style.color);
console.log(app.style.width);
console.log(app.style.height);
3.通过 getcomputedStyle 获取计算后的样式
var result = getComputedStyle(app)
//getPropertyValue 不能使用驼峰式命名
console.log(result.getPropertyValue('width'));
console.log(result.getPropertyValue('height'));
console.log(result.getPropertyValue('color'));
console.log(result.getPropertyValue('background-color'));
console.log(result.getPropertyValue('backgroundColor'));
4.[ ]语法 都可以获取
console.log(result['color']);
console.log(result['width']);
console.log(result['font-size']);
console.log(result['fontSize']);
5.获取不同浏览器下的样式
/**
* 封装一个getStyle方法 ,可以在不同浏览器下获取样式
* @obj 元素对象
* @key 属性名称
* return 获取的样式
**/
<style>
#app{
font-size:40px;
width: 200px;
height: 200px;
background-color: green;
border-bottom-color: #000;
border-bottom-width: 20px;
border-bottom-style: solid;
}
</style>
<div id="app" style="color: red;">
hello
</div>
函数
function getStyle(obj,key){
//能力检测:判断 浏览器是否支持 getcomponent 方法
//加window 如果没有这个方法不报错
if(window.getComputedStyle){
// 通过该方法获取
//已经确定了改方法存在,就可以直接使用了
//方法一:
return getComputedStyle(obj)[key]
// 方法二:
//将key驼峰式命名 转成 横线法
// key = key.replace(/([A-Z])/g,function(match,$1){
// //返回的是
// return '-' + $1.toLowerCase()
// })
// return getComputedStyle(obj).getPropertyValue(key)
}else{
var style = obj.currentStyle;
//如果有样式,可以获取
if(style){
//将横杠写法转成驼峰式命名
key = key.replace(/-([a-z])?/g,function(match,$1){
return ($1 || '').toUpperCase();
})
//返回样式
return style[key]
}else{
//没有样式
alert('你的浏览器不支持获取计算样式功能')
}
}
}
//测试
var app = document.getElementById('app')
console.log(getStyle(app,'color'));
console.log(getStyle(app,'fontSize'));
console.log(getStyle(app,'font-size'));