zoukankan      html  css  js  c++  java
  • 获取css样式,style、getComputedStyle及currentStyle的区别

    样式表有三种:

    内嵌样式:<div id="box" style="color:red">box</div>,style写在html中的为内嵌样式;

    内联样式:

    <style>
    #box{
        font-size: 25px;
        background-color: #ccc;
    }
    </style>

    在html页中直接写入<style></style>的为内联样式;

    外部样式:<link rel="stylesheet" href="css/style.css" />这种为外部样式。

    现在来测试一个小例子:

    <style>
    	#box{
    	   font-size: 25px;
    	   background-color: #ccc;
    	}
    </style>
    
    <div id="box" style="color:red">box</div>
    

    js代码:

    window.onload=function(){
            var box=document.getElementById('box');
            alert(box.style.color);  //弹出red   element.style[attr]对内嵌样式有效
            alert(box.style.fontSize);   //弹出空   从这里可以看出element.style[attr]只对内联样式无效
            alert(isStyle(box,'color'));   //使用isStyle方法,弹出rgb(255,0,0)
            alert(isStyle(box,'fontSize'));  //使用isStyle方法,弹出25px
    }
    
    /*通过元素节点和属性获取属性值*/
    function isStyle(ele,attr){
            if(window.getComputedStyle!='undefined'){   //兼容firefox
            	return window.getComputedStyle(ele,null)[attr];
            }else if(ele.currentStyle!='undefined'){    //兼容IE
                    return ele.currentStyle[attr];
            }	
    }

    要想获取内部样式以及外部样式需要通过getComputedStyle和currentStyle来获取,当然也可以获取内嵌样式。

  • 相关阅读:
    2.22
    LG P7077 函数调用
    2020/10/30 模拟赛 序列
    2020/10/27 模拟赛 数列
    2020/10/23 模拟赛 chip
    2020/10/23 模拟赛 escape
    2020/10/23 模拟赛 center
    LOJ#6581. 「ICPC World Finals 2019」断头路探测者
    LG P1587 [NOI2016]循环之美
    LG P4156 [WC2016]论战捆竹竿
  • 原文地址:https://www.cnblogs.com/heyujun-/p/6684195.html
Copyright © 2011-2022 走看看