如何从元素获取内联CSS样式属性

luk*_*999 9 css jquery inline properties

我有获取内联css样式属性的问题.

我试过这样做:

 var inline_css = $(this).attr("style");
Run Code Online (Sandbox Code Playgroud)

但...

它仅在元素没有内联样式之外的任何其他css属性时才有效...如:

.our_element {something: some;}
Run Code Online (Sandbox Code Playgroud)

任何想法如何从元素中获取具有许多其他CSS属性的内联CSS属性?

T.J*_*der 26

如果您指的是style属性中的样式,则可以直接在元素实例上访问它们:

var color = this.style.color;
Run Code Online (Sandbox Code Playgroud)

如果它属于属性(不通过样式表应用),那将color 给你style.

您使用的名称是camelCase,如果您使用文字符号,例如this.style.fontSize,或者您也可以使用带有括号表示法的CSS虚线样式this.style["font-size"].

只是为了完整性,如果你想要它来自style属性样式表的信息,jQuery的CSS函数就是这样:

var color = $(this).css("color");
Run Code Online (Sandbox Code Playgroud)

来自你的评论:

谢谢,但如果我想要所有属性我可以使用this.style ??

如果您希望将所有内联样式作为文本,请获取style属性(正如您所做)或使用this.style.cssText.

如果您想要所有样式(无论它们是否内联)作为对象,请使用getComputedStyle(或currentStyle在IE8等过时的浏览器上):

var style = window.getComputedStyle ? getComputedStyle(this) : this.currentStyle;
if (style) { // This will be true on major browsers
    var color = style.color; // Or whatever
}
Run Code Online (Sandbox Code Playgroud)

示例:

var div = document.querySelector(".foo");
snippet.log("div.style.fontSize: " + div.style.fontSize);
snippet.log("div.style.color: " + div.style.color);
snippet.log("div.style.cssText: " + div.style.cssText);
snippet.log("$(div).attr('style'): " + $(div).attr('style'));
snippet.log("$(div).css('fontSize'): " + $(div).css('fontSize') + " (note that's in pixels, probably, not pt)");
snippet.log("$(div).css('color'): " + $(div).css('color'));
Run Code Online (Sandbox Code Playgroud)
.foo {
  font-size: 14pt;
  color: green;
}
Run Code Online (Sandbox Code Playgroud)
<div class="foo" style="font-size: 12pt">
  This has an inline <code>font-size: 12pt</code> and
  CSS (not inline) giving <code>font-size: 14pt</code> and <code>color: green</code>.
</div>
<hr>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<!-- Script provides the `snippet` object, see http://meta.stackexchange.com/a/242144/134069 -->
<script src="http://tjcrowder.github.io/simple-snippets-console/snippet.js"></script>
Run Code Online (Sandbox Code Playgroud)