zoukankan      html  css  js  c++  java
  • js中style,currentStyle和getComputedStyle的区别以及获取css操作方法

    在js中,之前我们获取属性大多用的都是ele.style.border这种形式的方法,但是这种方法是有局限性的,该方法只能获取到行内样式,获取不了外部的样式.所以呢下面我就教大家获取外部样式的方法,因为获取外部的样式存在兼容性的问题,所以后面我还会教大家解决兼容性的方法.

    style:各大浏览器都兼容,能设置样式和获取样式,但是获取不了外部样式,如果写了行内没有的样式,返回的是空值

    写法:ele.style.attr(这样为获取),ele.style.attr="值";

    currentStyle属性和getComputedStyle属性不能设置属性,只能获取

    currentStyle:该属性只兼容IE,不兼容火狐和谷歌

     写法:ele.currentStyle["attr"]或者ele.currentStyle.attr;

    getComputedStyle:该属性是兼容火狐谷歌,不兼容IE

    写法:window.getComputedStyle(ele,null)[attr]获取是window.getComputedStyle(ele,null).attr

    下面我就贴上我的代码:

    var div=document.getElementsByTagName("div")[0];
            if(div.currentStyle){
                //IE上兼容
                console.log(div.currentStyle["width"]);
            }
            else{
                //火狐谷歌上兼容
                console.log(window.getComputedStyle(div,null)["width"]);
            }

    下面呢,我写了一个兼容性的方法,大家可以参考参考:

            var div=document.getElementsByTagName("div")[0];
    
            console.log(getStyle(div,"background-color"));
            function getStyle(ele,attr){
                if(window.getComputedStyle){
                    return window.getComputedStyle(ele,null)[attr];
                }
                return ele.currentStyle[attr];
            }

    说明:在IE中获取到的颜色是16进制的,在火狐谷歌中获取的颜色是rgb模式的

  • 相关阅读:
    2020软件工程作业04
    2020软件工程作业03
    2020软件工程作业02
    2020软件工程作业01
    Linux操作系统分析-课程学习总结报告
    结合中断上下文切换和进程上下文切换分析Linux内核的一般执行过程
    深入理解系统调用
    基于mykernel 2.0编写一个操作系统内核
    交互式多媒体图书平台的设计与实现
    码农放入自我修养之必备技能学习笔记
  • 原文地址:https://www.cnblogs.com/cythia/p/6721145.html
Copyright © 2011-2022 走看看