2016-09-28 38 views
3

我有一個元素,內聯CSS代碼在'樣式'屬性中。我在這個元素中添加了一個類,它在CSS樣式表中使用!important覆蓋了內聯樣式。獲取內聯CSS屬性值(即使其被覆蓋)

問題:如何獲得內聯CSS屬性值,即使它被樣式表中的CSS覆蓋?

當我使用$("div").css("background-size");它從樣式表CSS中獲取值,而不是被覆蓋的內聯CSS。

+0

jQuery使用計算樣式。 –

+0

'$(「div」)。attr(「style」);'它返回style屬性中的「inside」字符串。檢查[attr](http://api.jquery.com/attr/) –

回答

1

因爲jQuery使用computedStyles來獲取應用於元素的樣式。我相信,訪問DOM元素可能是一個「解決方案」

console.log(
 
    
 
    $('p').get(0).style.fontSize 
 
    
 
);
p { 
 
    font-size:20px !important; 
 
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script> 
 
<p style="font-size:40px;">Hello World</p>

可以擴展jQuery的功能,以及。

jQuery.fn.cssInline = function(prop) { 
 
    
 
    var e = $(this[0]).get(0); // get DOM element 
 
    // convert to camelCase; this may not be required. 
 
    var propCamelCase = prop.replace(/-([a-z])/g, function (g) { 
 
      return g[1].toUpperCase(); 
 
     }); 
 
    
 
    return e.style[propCamelCase]; 
 
    
 
}; 
 

 
console.log($('p').cssInline('font-size')); 
 
console.log($('p').cssInline('fontSize')); 
 
console.log($('p').cssInline('width'));
p { 
 
    font-size:20px !important; 
 
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script> 
 
<p style="font-size:40px;">Hello World</p>

+1

在這一點上,jQuery變得毫無用處。 'document.querySelector('p').style.fontSize'就夠了。 – Oriol

+0

榮譽!確實沒用。 OP已經標記了它 –