zoukankan      html  css  js  c++  java
  • js中style,currentStyle和getComputedStyle的区别

    在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];
     }
  • 相关阅读:
    选择筛选
    添加标签2 jquery 和JS
    最全的常用正则表达式大全
    Javascript和ECMAScript二三事
    display:none和visibility: hidden二三事
    说人话
    渐进增强和优雅降级
    css的优先级以及!important的使用
    解决VS如何同时打开两个工程(xp和win7)
    jQuery验证控件jquery.validate.js使用说明+中文API
  • 原文地址:https://www.cnblogs.com/menglong1214/p/10361980.html
Copyright © 2011-2022 走看看