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来获取,当然也可以获取内嵌样式。

  • 相关阅读:
    Spring Boot之@ImportResource、配置类、占位符表达式
    Spring Boot之测试类报错问题
    Spring Boot之@EnableAutoConfiguration源码解读
    Spring Boot之第一个程序及执行原理。
    eclipse中git使用中的冲突解决
    python画国旗
    第十六周进度
    个人课程总结
    人月神话之阅读笔记03
    第十五周进度
  • 原文地址:https://www.cnblogs.com/heyujun-/p/6684195.html
Copyright © 2011-2022 走看看