2014-09-30 65 views
0

我有一些內聯樣式的html元素加上自定義css屬性。 現在我可以訪問每個樣式屬性,但不能訪問我的自定義樣式屬性。javascript如何獲取html樣式的自定義屬性值

這是我的代碼。

<img id="myimg" class="ImgClass" style="overfolow:hidden;position:absolute;mycustomProp:100;top:15;left:20"> 

這裏我不能得到mycustomProp。

任何幫助?

+0

快速注: 「overfolow」 - > 「溢出」 – VictorKilo 2014-09-30 17:14:40

+0

http://javascript.info/tutorial/attributes-and-custom-properties – 2014-09-30 17:15:37

+0

阿維納什·巴布我可以訪問自定義屬性,但它不是我的問題我的問題是如何獲得自定義樣式屬性。 – anerjan 2014-09-30 17:18:34

回答

0

http://jsfiddle.net/phrjwgxk/

alert(getCustomStyle("myimg","mycustomProp")); 


function getCustomStyle(theId,theStyle) { 
    var styles=document.getElementById(theId).getAttribute("style").split(';'); 
    var astyle; 
    for(var i=0;i<styles.length;i++) { 
     astyle=styles[i].split(':'); 
     if(astyle[0]==theStyle) return (astyle[1]); 
    } 
    return undefined; 
} 
+0

我只是像你一樣手動完成它。反正謝謝:) – anerjan 2014-09-30 17:27:58

1

document.getElementById("myimg").getAttribute("style")檢索屬性。

document.getElementById("myimg").setAttribute("style",<string>)可以用來改變它。

+0

它發送整個混合數組,意味着它將每一個字符視爲數組元素。 – anerjan 2014-09-30 17:26:18

0

檢查

$("#myDiv").hasAttribute(name)

得到

$("#myDiv").getAttribute(name)

設置

$("#myDiv").setAttribute(name)

刪除

$("#myDiv").removeAttribute(name)