これはうまくいきませんか?
$('div').attr('style');
これをさらに解析したい場合:
var getStyles = function(element) {
// ensure element has style
if (! element.attr('style')) {
return {};
}
// init styles
var styles = {}
// parse style attr
$.each(element.attr('style').split(/\s*;\s*/), function(i,style) {
if (style.length) { // a style string ending in ; will cause an empty pair after splitting
pair = style.split(/\s*:\s*/);
styles[pair[0]] = pair[1];
}
});
return styles;
};
いくつかのテスト
// test an element with style attr
var element = $('<div style="float:left"></div>');
console.log(getStyles(element)); //=> {float: "left"}
console.log(getStyles(element).float); //=> left
console.log(getStyles(element).hello); //=> undefined
// test some element without style attr
var element2 = $('<p>hello</p>');
console.log(getStyles(element2).float); //=> undefined
console.log(getStyles(element2).hello); //=> undefined
// a bit more complex
var element3 = $('<div style="float:left; background-color:red; color:#555; opacity: 0.5 !important;"></div>');
console.log(getStyles(element3)); //=> {float: "left", opacity: "0.5 !important", background-color: "red", color: "#555"}
console.log(getStyles(element3).float); //=> left
console.log(getStyles(element3).opacity) //=> 0.5 !important;
console.log(getStyles(element3)["background-color"]); //=> red
</p>
jsFiddle での動作を確認してください
</p>