currentstyle 和 getComputedStyle—JS学习笔记2015-6-17(第59天)

getComputedStyle 和 currentStyle

获得到的是计算机(浏览器)计算后的样子;

ie8 以及更早ie浏览器,无法兼容该方法;

可以使用currentStyle  // 不过标准浏览器下却不兼容;

这两种方法的适用范围和注意事项(以后会有解决方案,比如正则, 学东西不要死板):

复合样式获取不到,会有兼容性问题,比如:background

想到得到背景颜色, 应该是backgroundColor

获取单一样式,而不要获取复合样式

不要有空格;

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

<!DOCTYPE HTML>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>无标题文档</title>
<style>
div { width:100px; height:120px; background:red; }
</style>
<script src="miaov.js"></script>
<script>
$(function(){
    
    // $('div1').style.width = '300px';
    
    
    $('btn1').onclick = function  (){
        // alert( $('div1').style.width );
        // $('div1').style.cssText = '350px;';
        
        // alert( getComputedStyle( $('div1') ).width );            // IE6 7 8 不兼容
        
        // alert( $('div1').currentStyle.width );                                        // 标准浏览器不兼容
        /*
        if( $('div1').currentStyle ){
            alert( $('div1').currentStyle.width );
        } else {
            alert( getComputedStyle( $('div1'), 250 ).width );
            // FF 4.0 之前
        }
        */
        
        // alert( getStyle( $('div1'), 'width' ) );
        // alert( getStyle( $('div1'), 'height' ) );
        
        alert( getStyle( $('div1'), 'marginRight' ) );
        
        /*
                获取到的是计算机(浏览器)计算后的样式
                
                background: url() red ……        复合样式(不要获取)
                backgroundColor                                    单一样式(不要用来做判断)
                
                不要有空格
                
                不要获取未设置后的样式:不兼容
        */
    };
});


</script>
</head>

<body>

<input id="btn1" type="button" value="按钮" />
<div id="div1"></div>

</body>
</html>
原文地址:https://www.cnblogs.com/zhangxg/p/4584670.html