在对网页进行调试的过程中,经常会用到js来获取元素的CSS样式,方法有很多很多,现在仅把我经常用的方法总结如下:
1. obj.style:这个方法只能JS只能获取写在html标签中的写在style属性中的值(style=”…”),而无法获取定义在<style type="text/css">里面的属性。
复制代码 代码如下:
<span><!DOCTYPE html PUBLIC “-//W3C//DTD XHTML 1.0 Transitional//EN” ““>
<html xmlns=”“>
<head>
<meta http-equiv=”Content-Type” content=”text/html; charset=utf-8″ />
<title>JS获取CSS属性值</title>
<style type=”text/css”>
<!–
.ss{color:#cdcdcd;}
–>
</style>
</head>
<body>
<div id=”css88″ class=”ss” style=”width:200px; height:200px; background:#333333″>JS获取CSS属性值</div>
<script type=”text/javascript”>
alert(document.getElementById(“css88″).style.width);//200px
alert(document.getElementById(“css88″).style.color);//空白
</script>
</body>
</html> </span>
复制代码 代码如下:
<span><!DOCTYPE html>
<html>
<head>
<title>计算元素样式</title>
<style>
#myDiv {
background-color:blue;
width:100px;
height:200px;
}
</style>
<body>
<div id ="myDiv"></div>
<script>
var myDiv = document.getElementById("myDiv");
var computedStyle = document.defaultView.getComputedStyle(myDiv, null);
alert(computedStyle.backgroundColor); //"red"
alert(computedStyle.width); //"100px"
alert(computedStyle.height); //"200px"
alert(computedStyle.border); //在某些浏览器中是“1px solid black”
</script>
</body>
</head>
</html></span>
复制代码 代码如下:
<span>var myDiv = document.getElementById("myDiv");
var computedStyle = myDiv.currentStyle;
alert(computedStyle.backgroundColor); //"red"
alert(computedStyle.width); //"100px"
alert(computedStyle.height); //"200px"
alert(computedStyle.border); //undefined</span>
复制代码 代码如下:
<span>function getCSS(div){
return document.defaultView.getComputedStyle(div, null);
//return div.currentStyle;//没用过,IE
}</span>
新闻热点
疑难解答
图片精选