• js获取css样式方法


    一、CSS样式共有三种:内联样式(行间样式)、内部样式、外部样式(链接式和导入式)

    <div id="a" style=" 100px;height: 100px;"></div>
    <style type="text/css">
        #a{
            width: 100px;
            height: 100px;
        }
    </style>
    <body>
        <div id="a"></div>
    </body>
    <!-- 外部CSS样式 -->
    <!-- 链接式 -->
    <link rel="stylesheet" type="text/css" href="css/temp.css"/>
    <style type="text/css">
        <!-- 导入式 -->
        @import url("css/style.css");
    </style>

    优先级:一般情况下:内联样式  >  内部样式  >  外部样式
    特殊情况下:当外部样式放在内部样式之后,外部样式将覆盖内部样式。

    <style type="text/css">
        #a{
            width: 200px;
            height: 200px;
            background-color: red;
        }
    </style>
    <link rel="stylesheet" type="text/css" href="css/temp.css"/>

    二、js获取css样式

    1、内联样式(行间样式)的获取

    <div id="a" style=" 100px;height: 100px;background-color: blue;"></div>
    function temp(){
        var a=document.getElementById("a");
        var aColor=a.style.backgroundColor;
        var aWidth=a.style["width"];
        alert(aColor+"  "+aWidth);
    //    rgb(0,0,255)  100px
    }

    2、内部样式的获取

    <style type="text/css">
        #a{
            width: 200px;
            height: 200px;
            background-color: red;
        }
    </style>
    <body>
        <div id="a"></div>
    </body>
    function temp(){
    //  非IE浏览器
        var a=document.getElementById("a");
        var aStyle=getComputedStyle(a);
        var aColor=aStyle.backgroundColor;
        var aWidth=aStyle["width"];
        alert(aColor+"  "+aWidth);
    //  rgb(255,0,0)  200px
    //  IE浏览器
    //  var a=document.getElementById("a");
    //  var aStyle=a.currentStyle;
    //  var aColor=aStyle.backgroundColor;
    //  var aWidth=aStyle["width"];
    //  alert(aColor+"  "+aWidth);
    //  red  200px
    }

    3、外部样式的获取(同内部样式)

    <!-- css文件 -->
    #a{
        width: 300px;
        height: 300px;
        background-color: #4F5F6F;
    }
  • 相关阅读:
    cmd net use
    Linux虚拟机安装VMware Tools
    转:完成端口(Completion Port)详解
    很幽默的讲解六种Socket IO模型
    重新学习二叉树作的几道习题
    RuntimeException和Exception区别
    不同概率的抽奖
    SpringMVC的几种返回方式
    mybatis动态sql trim
    Tomcat 7最大并发连接数的正确修改方法
  • 原文地址:https://www.cnblogs.com/lixiang1993/p/7244258.html
Copyright © 2020-2023  润新知