2017-10-20 35 views
3

我想要獲得動態設置的所有樣式(它適用於內聯樣式)。如何在jQuery中獲取所有動態設置的內聯樣式CSS?

例如

<span class="text" style="color: rgb(128, 128, 255); font-size: 24px;">Name</span> 

我想樣式屬性的一個JS變量的值,並將其保存。 我已經使用jQuery的.attr(「風格」)試過了,但它給不確定

此外,由於這裏建議How to get inline CSS style property from element使用

getComputedStyle 

,但得到的風格,我需要提到的所有風格如

var el = document.querySelector("selector") 
console.log(el.style.SomeStyle); 

但有各種樣式,用戶可以動態設置。 那麼,我是否需要單獨提及所有聯機風格或者是否有更好的方法來獲取?

預先感謝任何幫助

void's評論更新:

如這裏所描述Can jQuery get all CSS styles associated with an element?

marknadal曾寫道,檢索內嵌和外部樣式的功能,但我只是不管連接的所有css類如何,都需要內聯樣式

+0

https://stackoverflow.com/questions/754607/can-jquery-get-all-css-styles-associated-with-an-element – void

回答

2

您可以使用getAttribute

const el = document.querySelector('my-element'); 
const styleStr = el.getAttribute('style'); 

例如,以下內容:

<div style="color:blue;display:flex;"></div> 

會產生:

'color:blue;display:flex;' 

然後,您可以使用正則表達式或其他東西來解析它。我建議轉換成一個數組或一個類似的結構數組而不是一個對象,因爲你可能不確定哪些值是可用的(這是一個簡單的方法,這可能是一種更有效的方法分解它。我把它留給你):

// gives [ ['color', 'blue'], ['display', 'flex'] ] 
str.slice(0, str.length - 1).split(';').map(x => x.split(':')) 

你可以轉換成一個對象,並使用for in環連同obj.hasOwnProperty(key)爲好。

jQuery的替代:

const els = $('my-element'); 
els.each((i, el) => { 
    const styleStr = els.attr('style'); 
    const styles = styleStr.slice(0, styleStr.length - 1).split(';').map(x => x.split(':')); 
}); 
+0

[treyhakanson](https://stackoverflow.com/users/5495358/treyhakanson),請參閱我在FRS的答案中發佈的評論。謝謝 –

+1

你可以使用'querySelectorAll'並迭代它,它會工作。在jQuery中,解決方案是相同的,只需使用'.attr'而不是'getAttribute'。我知道你說過你試過這個,但它不起作用,但是你必須在其他地方有一個錯誤,因爲我之前使用過'.attr('style')',它工作正常 – treyhakanson

+1

的確我犯了一些錯誤,現在。非常感謝 –

0

您可以迭代o bject下元素的「風格」字段可用如下:

警告該對象包含也元件的所有可能的造型(與非數值屬性鍵),與例如這樣循環對於(sth in styles)將不會工作。您需要按照如下所示以類似數組的方式迭代樣式。

var el = document.querySelector("selector"); 
var styles = el.style; 

for (var i = 0, len = styles.length; i < len; ++i) { 
    var name = styles[i]; 
    var value = styles[value]; 

    console.log(name); // shows style name, e.g.: color, padding, etc 
    console.log(value); // shows style value, e.g.: #fff, 20px, etc 
} 
+0

的可能的複製[FRS ](https://stackoverflow.com/users/8805801/frs)是否有可能在jQuery中?因爲這個解決方案不適合我,因爲我有各種連續的元素,我需要迭代。 –