zoukankan      html  css  js  c++  java
  • JS获取元素属性、样式getComputedStyle()和currentStyle方法兼容性问题

    1、 getComputedStyle()  方法获取到的是经过计算机/浏览器计算后的样式

      getComputedStyle($("#div")).width;

      兼容性:IE6 7 8不兼容

    2、 $("#div").currentStyle(width);

      兼容性:FF不兼容、标准浏览器不兼容

    3、$("div").style.width   只能得到行间样式,如果样式没写在行业,就得不到了

      $("#div").style.background = 'url()';

    4、$("#div").style.cssText = "350px;";    可以用来写入样式

    属性判断法处理浏览器兼容问题:

    if ($("#div").currentStyle){

      alert($("#div").currentStyle.width);

    }else{

      alert(getComputedStyle($("#div"),'old ff is 250').width);           // ff4.0 前需要跟个参数才能兼容,可以不写,反正现在火狐版本都已经很高了

    }

    封装方法:

    function getStyle (obj,attr){ 

      if (obj.currentStyle){

        return obj.currentStyle[attr];

      }else{

        return getComputedStyle(obj)[attr];

      }

    }

    alert(getStyle($("#div1"),'width'));

    改成三木运算

    function getStyle (obj,attr){

      return obj.currentStyle ? obj.currentStyle[attr] : return getComputedStyle(obj)[attr] 

    }

    alert(getStyle($("#div1"),'width'));

    alert(getStyle($("#div1"),'height'));

    注意问题:

    1、 复合样式  background:url() red …… 获取到的会有兼容性问题

      变为单一样式:backgroundColor (不要用来做判断)

    2、 想要获取的样式要拼写正确,不要有空格

    3、 不要获取未设置后的样式:不兼容

  • 相关阅读:
    自动化无线网破解工具wifite2
    用Python实现Excel的读写
    Python常见问题系列
    集群搭建
    redis进阶
    android中实现简单的聊天功能
    android中使用setOnKeyListener响应输入事件
    android中使用spinner组件,以key,value的方式
    android中使用spinner组件
    android中使用Nine-Patch图片
  • 原文地址:https://www.cnblogs.com/YYvam1288/p/4914151.html
Copyright © 2011-2022 走看看