zoukankan      html  css  js  c++  java
  • JS之DOM篇查询计算样式

    CSS全称是层叠样式表,元素的最终渲染结果是由多个CSS样式叠加后的结果,可以通过查询计算样式获得最终的叠加结果

    getComputedStyle()

    元素的计算样式(computedStyle)是用一个 CSSStyleDeclaration对象来表示的,计算样式是只读的,主要通过getComputedStyle()方法实现

    getComputedStyle()方法接收两个参数:要取得计算样式的元素和一个伪元素字符串。如果不需要伪元素信息,第二个参数可以是null或者直接省略。

    getComputedStyle()方法原本是window对象下的方法,后来“DOM2级样式”增强了document.defaultView,也提供了getComputedStyle()方法,现在getComputedStyle()方法一共有下面3种写法:

    1、document.defaultView.getComputedStyle(div).width
    
    2、window.getComputedStyle(div).width
    
    3、getComputedStyle(div).width
    
    <div id="test" style=" 100px;"></div>
    <script>
    // 结果都是 '100px'
    console.log(document.defaultView.getComputedStyle(test).width);
    console.log(window.getComputedStyle(test).width);
    console.log(getComputedStyle(test).width);
    </script>
    

    伪元素

    第二个参数代表伪元素字符串,包括"::before"、"::after"、"::first-line"、"::first-letter"等,如果设置为null或省略不写,则返回自身元素的CSSStyleDeclaration对象

    关于伪元素和伪类的区别移步至此

    <style>
    #test::before{
      content:'';
      display: inline-block;
      20px;
    }
    </style>
    <div id="test" style=" 100px;"></div>
    <script>
    console.log(getComputedStyle(test,'::before').width); //'20px'
    </script>
    

    注意事项

    1. 对于font、background、border等复合样式,各浏览器处理不一样。chrome会返回整个复合样式,而IE9+、firefox和safari则输出空字符串''
    <div id="test" style="font-size:20px"></div>
    <script>
    // chrome返回normal normal 400 normal 20px / normal "Microsoft YaHei",其他浏览器返回''
    console.log(getComputedStyle(test).font);
    </script>
    
    1. 不论以什么格式设置颜色,浏览器都以rgb()或rgba()的形式输出
    1. 类似百分比等相对单位会转换为绝对值
    <div id="test" style="20%;"></div>
    <script>
    console.log(getComputedStyle(test).width); // '170.797px'
    </script>
    
    优秀文章首发于聚享小站,欢迎关注!
  • 相关阅读:
    razor在App_Code中使用ActionLink无效的解决方案
    科技的进步会给人带来幸福么?
    C6000系列之C6455 DSP的EMIFA接口
    C6000系列之C6455DSP的GPIO模块
    C语言文件操作与例子
    C语言中fscanf函数读取double型浮点数的问题
    MATLAB读取CCS保存的数据
    CCS 3.3 操作C函数读写文件
    复数矩阵乘法C语言实现
    C6000系列之C6455DSP的中断系统
  • 原文地址:https://www.cnblogs.com/yesyes/p/15352417.html
Copyright © 2011-2022 走看看