JavaScript获取CSS样式
语法:
nodeObject.style.cssProperty
其中,nodeObject 为节点对象,cssProperty 为CSS属性。
例如:
document.getElementById("demo").style.height;
document.getElementById("demo").style.border;注意:对于由 “ - ” 分隔的CSS属性,要去掉 “ - ” ,并将 “ - ” 后的第一个字母大写。例如:
background-color 要写作 backgroundColor
line-height 要写作 lineHeight
例如:
document.getElementById("demo").style. backgroundColor;
document.getElementById("demo").style.lineHeight;举例,获取 id="demo" 的节点的样式:
<div id="demo" style="height:50px; width:250px; margin-top:10px; text-align:center; line-height:50px; background-color:#ccc;">
点击这里获取CSS样式
</div>
<script type="text/javascript">
document.getElementById("demo").onclick=function(){
alert(
"高度:"+this.style.height+"\n"+
"宽度:"+this.style.width+"\n"+
"上边距:"+this.style.marginTop+"\n"+
"对齐:"+this.style.textAlign+"\n"+
"行高:"+this.style.lineHeight+"\n"+
"背景颜色:"+this.style.backgroundColor
);
}
</script>对上述代码稍作修改,将 CSS 样式与 HTML 分开:
<style>
#demo{
height:50px;
width:250px;
margin-top:10px;
text-align:center;
line-height:50px;
background-color:#ccc;
}
</style>
<div id="demo">
点击这里获取CSS样式
</div>
<script type="text/javascript">
document.getElementById("demo").onclick=function(){
alert(
"高度:"+this.style.height+"\n"+
"宽度:"+this.style.width+"\n"+
"上边距:"+this.style.marginTop+"\n"+
"对齐:"+this.style.textAlign+"\n"+
"行高:"+this.style.lineHeight+"\n"+
"背景颜色:"+this.style.backgroundColor
);
}
</script>可以发现,将 CSS 样式与HTML代码分开后无法获取CSS样式。这是因为
nodeObject.style.cssProperty
获取的是DOM节点上 style 属性定义的样式,如果不存在 style 属性,或者 style 属性没有定义相应的样式,则是无法获取的。
也就是说,JavaScript 不会到 <style> 标签或者 CSS 文件去获取相应的样式,只能获取 style 属性定义的样式。
新建文件
<!DOCTYPE HTML>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>无标题文档</title>
<div id="demo" style="height:50px; width:250px; margin-top:10px; text-align:center; line-height:50px; background-color:#ccc;">
点击这里获取CSS样式
</div>
<script type="text/javascript">
document.getElementById("demo").onclick=function(){
alert(
"高度:"+this.style.height+"\n"+
"宽度:"+this.style.width+"\n"+
"上边距:"+this.style.marginTop+"\n"+
"对齐:"+this.style.textAlign+"\n"+
"行高:"+this.style.lineHeight+"\n"+
"背景颜色:"+this.style.backgroundColor
);
}
</script>
</head>
<body>
</body>
</html>
预览
Clear
- 课程推荐
- 课件下载
课件暂不提供下载,工作人员正在整理中,后期请多关注该课程~ 















