js获取非行间样式

相关知识:

window.getComputedStyle:  

  Window.getComputedStyle() 方法给出应用活动样式表后的元素的所有css属性的值,并解析这些值可能包含的任何基本计算。
  语法:let style = window.getComputedStyle(element, [pseudoElt]);
    pseudoElt :指定一个要匹配的伪元素的字符串。必须对普通元素省略(或null)。
    返回的样式是一个实时的 CSSStyleDeclaration 对象,当元素的样式更改时,它会自动更新本身。

  与伪元素一起使用:
        let h3 = document.querySelector('h3'),
        result = getComputedStyle(h3, '::after').content;
  getComputedStyle(odiv,false)这里的两个参数,第一个参数代表要获取那个元素的样式, 第二个是解决FF较低版本的写法,而对于高版本的可以不用写。

 注在firefox3.6上访问子框架内的样式 (iframe)必须使用 document.defaultView.getComputedStyle ,其他可使用window.getComputedStyle

Element.currentStyle

  表示由全局样式表,内联样式和HTML属性指定的对象的级联格式和样式。Element.currentStyle 是一个与 window.getComputedStyle方法功能相同的属性。
  这个属性实现在旧版本的IE浏览器中.
常用方法:getAttributegetPropertyValuesetAttributesetProperty...
常用属性:backgroundbackgroundColorborderborderBottom...

Element.runtimeStyle 

  Element.runtimeStyle 是一个自带的属性, HTMLElement.style 相似。相比而言, runtimeStyle 具有更高的优先级,但它并不会修改 style 的  content 属性。runtimeStyle 在旧版的IE浏览器上是可用的。

html:

<body>
<div style="background:red;" id ="div1"></div>
<div style="background:green;" id ="div2"></div>
</body>

 js:

//获取行间样式
    var oDiv=document.getElementById("div1");
    console.log(oDiv.style.background);
/*获取非行间样式*/
function getStyle1(obj,attr){
    if(obj.currentStyle){//IE
        return obj.currentStyle[attr];
    }else{
        //return window.getComputedStyle(obj,false)[attr];
        // 或 return document.defaultView.getComputedStyle(obj,null).getPropertyValue(attr);
        return document.defaultView.getComputedStyle(obj,false)[attr];
    }
}
var  oDiv2  =document.getElementById("div2");
   console.log(getStyle1(oDiv2,"background"));
/*兼容1*/
/*https://stackoverflow.com/questions/9183555/whats-the-point-of-document-defaultview*/
    function getStyle2(element, styleProp) {
        var view = element.ownerDocument && element.ownerDocument.defaultView ?
            element.ownerDocument.defaultView : window;

        return view.getComputedStyle ?
            view.getComputedStyle(element,null).getPropertyValue(styleProp) :
            element.currentStyle ?
                element.currentStyle[styleProp] : null;
    }

jquery中兼容处理(jQuery JavaScript Library v1.12.4)

/*jquery中兼容处理*/

    var     ralpha = /alpha([^)]*)/i,
        ropacity = /opacitys*=s*([^)]*)/i,

        // swappable if display is none or starts with table except
        // "table", "table-cell", or "table-caption"
        // see here for display values:
        // https://developer.mozilla.org/en-US/docs/CSS/display
        rdisplayswap = /^(none|table(?!-c[ea]).+)/,
        rnumsplit = new RegExp( "^(" + pnum + ")(.*)$", "i" ),

        cssShow = { position: "absolute", visibility: "hidden", display: "block" },
        cssNormalTransform = {
            letterSpacing: "0",
            fontWeight: "400"
        },

        cssPrefixes = [ "Webkit", "O", "Moz", "ms" ],
        emptyStyle = document.createElement( "div" ).style;
    var rnumnonpx = new RegExp( "^(" + pnum + ")(?!px)[a-z%]+$", "i" );
var getStyle,curCSS,
    rposition = /^(top|right|bottom|left)$/;
if(window.getComputedStyle){
    // Support: IE<=11+, Firefox<=30+ (#15098, #14150)
    // IE throws on elements created in popups  IE在弹窗中创建元素时抛出错误
    // FF meanwhile throws on frame elements through "defaultView.getComputedStyle"
    // 同时FF在框架frame中使用"defaultView.getComputedStyle"会抛出错误

    getStyle = function(elem){
        //Node.ownerDocument 只读属性会返回当前节点的顶层的 document 对象。
        //注意:被此属性返回的 document 对象是在实际的HTML文档中的所有子节点所属的主对象。
        // 如果在文档节点自身上使用此属性,则结果是null。
       //var win = document.defaultView;
        // 在浏览器中,该属性返回当前 document 对象所关联的 window 对象,如果没有(ie8?),会返回 null。
      // jquery(#15098, #14150)  它曾经使用window.getComputedStyle,无论哪个文档拥有该节点,并且现在使用(看似更正确的)
       // ownerDocument.defaultView访问相关窗口(例如,在iframe或弹出窗口中)并在其中调用getComputedStyle。
        var view = elem.ownerDocument.defaultView;
       // opener 属性是一个可读可写的属性,可返回对创建该窗口的 Window 对象的引用。
        //opener 属性非常有用,创建的窗口可以引用创建它的窗口所定义的属性和函数。
        //注释:只有表示顶层窗口的 Window 对象的 operner 属性才有效,表示框架的 Window 对象的 operner 属性无效。
        //  opener代表打开自身的那个窗口,比如窗口a.html打开窗口b.html。
        //   如果靠window.open方法,则对于窗口b.html,self代表b.html自己,而opener代表窗口a.html。
        //   myWindow=window.open('','MyName','width=200,height=100')
        //   myWindow.document.write("This is 'myWindow'")
        //   myWindow.focus()
        //   myWindow.opener.document.write("This is the parent window")

        if(!view||!view.opener){//如果是框架则使用window
            view = window;
        }
    }
    curCSS = function( elem, name, computed ) {
        var width, minWidth, maxWidth, ret,
            style = elem.style;

        computed = computed || getStyles( elem );

        // getPropertyValue is only needed for .css('filter') in IE9, see #12537
        //getPropertyValue仅在IE9中.css('filter')需要,请参见#12537;element.css('filter') returns undefined in IE9
        ret = computed ? computed.getPropertyValue( name ) || computed[ name ] : undefined;

        // Support: Opera 12.1x only
        // Fall back to style even without computed
        // computed is undefined for elems on document fragments  对文档片段上的elems计算undefined
        if ( ( ret === "" || ret === undefined ) && !jQuery.contains( elem.ownerDocument, elem ) ) {
            ret = jQuery.style( elem, name );
        }

        if ( computed ) {

            // A tribute to the "awesome hack by Dean Edwards"
            // Chrome < 17 and Safari 5.0 uses "computed value"
            // instead of "used value" for margin-right
            // Safari 5.1.7 (at least) returns percentage for a larger set of values,
            // but width seems to be reliably pixels
            // this is against the CSSOM draft spec:
            // http://dev.w3.org/csswg/cssom/#resolved-values
            // Chrome < 17 and Safari 5.0 的margin-right使用“计算值”而不是“应用值”
            //Safari 5.1.7 (at least)返回一组百分比,但宽度似乎是可靠的像素,这是有背CSSOM草案规范
            if ( !support.pixelMarginRight() && rnumnonpx.test( ret ) && rmargin.test( name ) ) {

                // Remember the original values
                width = style.width;
                minWidth = style.minWidth;
                maxWidth = style.maxWidth;

                // Put in the new values to get a computed value out
                style.minWidth = style.maxWidth = style.width = ret;
                ret = computed.width;

                // Revert the changed values
                style.width = width;
                style.minWidth = minWidth;
                style.maxWidth = maxWidth;
            }
        }

        // Support: IE
        // IE returns zIndex value as an integer.
        return ret === undefined ?
            ret :
            ret + "";
    };
}else if(documentElement.currentStyle){
    getStyle = function(elem){
        return elem.currentStyle;
    }
    curCSS = function( elem, name, computed ) {
        var left, rs, rsLeft, ret,
            style = elem.style;

        computed = computed || getStyles( elem );
        ret = computed ? computed[ name ] : undefined;

        // Avoid setting ret to empty string here
        // so we don't default to auto
        // 避免将ret设置为空字符串,因此我们不会默认为auto
        if ( ret == null && style && style[ name ] ) {
            ret = style[ name ];
        }

        // From the awesome hack by Dean Edwards
        // http://erik.eae.net/archives/2007/07/27/18.54.15/#comment-102291

        // If we're not dealing with a regular pixel number
        // but a number that has a weird ending, we need to convert it to pixels
        // but not position css attributes, as those are
        // proportional to the parent element instead
        // and we can't measure the parent instead because it
        // might trigger a "stacking dolls" problem
        //如果我们不处理正常的像素数
        // 但一个数字有一个奇怪的结尾,我们需要将其转换为像素
        //但不是位置css属性,因为它们与父元素成比例,我们不能测量父级元素,
        // 因为它可能会触发“堆叠”问题
        if ( rnumnonpx.test( ret ) && !rposition.test( name ) ) {

            // Remember the original values
            left = style.left;
            rs = elem.runtimeStyle;
            rsLeft = rs && rs.left;

            // Put in the new values to get a computed value out
            if ( rsLeft ) {
                rs.left = elem.currentStyle.left;
            }
            style.left = name === "fontSize" ? "1em" : ret;
            ret = style.pixelLeft + "px";

            // Revert the changed values
            style.left = left;
            if ( rsLeft ) {
                rs.left = rsLeft;
            }
        }

        // Support: IE
        // IE returns zIndex value as an integer.
        return ret === undefined ?
            ret :
            ret + "" || "auto";
    };

    jQuery.extend( {

        // Add in style property hooks for overriding the default
        // behavior of getting and setting a style property
        //添加样式属性钩子,以覆盖获取和设置样式属性的默认行为
        cssHooks: {
            opacity: {
                get: function( elem, computed ) {
                    if ( computed ) {

                        // We should always get a number back from opacity
                        var ret = curCSS( elem, "opacity" );
                        return ret === "" ? "1" : ret;
                    }
                }
            }
        },

        // Don't automatically add "px" to these possibly-unitless properties
        //不要自动添加“px”到这些可能无单位的属性
        cssNumber: {
            "animationIterationCount": true,
            "columnCount": true,
            "fillOpacity": true,
            "flexGrow": true,
            "flexShrink": true,
            "fontWeight": true,
            "lineHeight": true,
            "opacity": true,
            "order": true,
            "orphans": true,
            "widows": true,
            "zIndex": true,
            "zoom": true
        },

        // Add in properties whose names you wish to fix before
        // setting or getting the value
        //在设置或获取值之前添加要修复其名称的属性
        cssProps: {

            // normalize float css property
            // (IE uses styleFloat instead of cssFloat)    support.cssFloat = !!div.style.cssFloat;
            "float": support.cssFloat ? "cssFloat" : "styleFloat"
        },

        // Get and set the style property on a DOM Node 获取和设置DOM节点上的style属性
        style: function( elem, name, value, extra ) {

            // Don't set styles on text and comment nodes 不要在文本和注释节点上设置样式
            if ( !elem || elem.nodeType === 3 || elem.nodeType === 8 || !elem.style ) {
                return;
            }

            // Make sure that we're working with the right name 确保我们正在使用正确的名称
            var ret, type, hooks,
                origName = jQuery.camelCase( name ),
                style = elem.style;

            name = jQuery.cssProps[ origName ] ||
                ( jQuery.cssProps[ origName ] = vendorPropName( origName ) || origName );

            // gets hook for the prefixed version
            // followed by the unprefixed version
            hooks = jQuery.cssHooks[ name ] || jQuery.cssHooks[ origName ];

            // Check if we're setting a value
            if ( value !== undefined ) {
                type = typeof value;

                // Convert "+=" or "-=" to relative numbers (#7345)
                if ( type === "string" && ( ret = rcssNum.exec( value ) ) && ret[ 1 ] ) {
                    value = adjustCSS( elem, name, ret );

                    // Fixes bug #9237
                    type = "number";
                }

                // Make sure that null and NaN values aren't set. See: #7116
                if ( value == null || value !== value ) {
                    return;
                }

                // If a number was passed in, add the unit (except for certain CSS properties)
                if ( type === "number" ) {
                    value += ret && ret[ 3 ] || ( jQuery.cssNumber[ origName ] ? "" : "px" );
                }

                // Fixes #8908, it can be done more correctly by specifing setters in cssHooks,
                // but it would mean to define eight
                // (for every problematic property) identical functions
                if ( !support.clearCloneStyle && value === "" && name.indexOf( "background" ) === 0 ) {
                    style[ name ] = "inherit";
                }

                // If a hook was provided, use that value, otherwise just set the specified value
                //如果提供了一个钩子,请使用该值,否则只需设置指定的值
                if ( !hooks || !( "set" in hooks ) ||
                    ( value = hooks.set( elem, value, extra ) ) !== undefined ) {

                    // Support: IE
                    // Swallow errors from 'invalid' CSS values (#5509)
                    try {
                        style[ name ] = value;
                    } catch ( e ) {}
                }

            } else {

                // If a hook was provided get the non-computed value from there
                if ( hooks && "get" in hooks &&
                    ( ret = hooks.get( elem, false, extra ) ) !== undefined ) {

                    return ret;
                }

                // Otherwise just get the value from the style object
                return style[ name ];
            }
        },

        css: function( elem, name, extra, styles ) {
            var num, val, hooks,
                origName = jQuery.camelCase( name );

            // Make sure that we're working with the right name
            name = jQuery.cssProps[ origName ] ||
                ( jQuery.cssProps[ origName ] = vendorPropName( origName ) || origName );

            // gets hook for the prefixed version
            // followed by the unprefixed version
            hooks = jQuery.cssHooks[ name ] || jQuery.cssHooks[ origName ];

            // If a hook was provided get the computed value from there
            if ( hooks && "get" in hooks ) {
                val = hooks.get( elem, true, extra );
            }

            // Otherwise, if a way to get the computed value exists, use that
           //如果存在获取计算值的方法,请使用该方法
            if ( val === undefined ) {
                val = curCSS( elem, name, styles );
            }

            //convert "normal" to computed value   "normal"转换为计算值
            if ( val === "normal" && name in cssNormalTransform ) {
                val = cssNormalTransform[ name ];
            }

            // Return, converting to number if forced or a qualifier was provided and val looks numeric
            //返如果被强制或提供限定符和val看起来数字 返回时转换为数字,
            if ( extra === "" || extra ) {
                num = parseFloat( val );
                return extra === true || isFinite( num ) ? num || 0 : val;
            }
            return val;
        }
    } );
}
View Code

参考:

https://developer.mozilla.org/zh-CN/docs/Web/API/Element/currentStyle
https://msdn.microsoft.com/en-us/library/ms535231(v=vs.85).aspx
http://www.cnblogs.com/xiaominwu/p/4348064.html
https://www.w3.org/TR/DOM-Level-2-Style/css.html#CSS-OverrideAndComputed
原文地址:https://www.cnblogs.com/xiaozhuyuan/p/7676823.html