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瀏覽器中.
常用方法:getAttribute、getPropertyValue、setAttribute、setProperty...
常用屬性:background、backgroundColor、border、borderBottom...
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 = /opacity\s*=\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
js獲取非行間樣式