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>
提交重置代码
章节
笔记
提问
课件
反馈
捐赠

弹指间学会JavaScript 教程