一、获取样式注意的问题:
点击按钮获取div的样式:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>获取样式内容</title>
<style>
div{
width: 100px;
height: 120px;
background: red;
}
</style>
<script src="../JS.js"></script>
<script>
$(function(){
$('btn1').onclick = function () {
// alert($('div1').style.width); 不支持这种写法
//alert(getComputedStyle($('div1')).width );//IE6,7,8不兼容
//alert($('div1').currentStyle.width);//标准浏览器不兼容(Google,Firefox)
// if($('div1').currentStyle){
// alert($('div1').currentStyle.width);
// }else {
// alert(getComputedStyle($('div1')).width );
// }
alert(getStyle('div1','background-color'));
//alert(getStyle('div1','height'));
}
})
function getStyle(obj,attr){
return $(obj).currentStyle?$(obj).currentStyle[attr]:getComputedStyle($(obj))[attr];
}
</script>
</head>
<body>
<input type="button" value="按钮" id="btn1" />
<div id="div1"></div>
</body>
</html>
涉及到的两种方法:
①getComputedStyle(对象).属性值
缺点是IE6,7,8不兼容
②对象.currentStyle.属性值
缺点是标准浏览器不兼容
把两个方法整合成一个兼容的方法getStyle()来使用
二、注意getStyle(对象,属性值)的使用:
获取到的是计算机(浏览器)计算后的样式
background: url() red …… 复合样式(不要获取)
backgroundColor 单一样式(不要用来做判断)
不要有空格
不要获取未设置后的样式:不兼容
网友评论