用JS获取当前应用样式 [英] Get current applied style with JS

查看:96
本文介绍了用JS获取当前应用样式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在看这篇文章



其中确认了如果你这样做的话

  div.style.color 

返回颜色应用到div。



但是,这似乎只返回一个结果,如果风格是内联应用于元素?



当样式通过样式表(或标签)而不是直接内联应用时,如何返回应用于元素的样式?

请参阅下面的示例。



console.log(document.getElementById('content ).style.backgroundColor);的console.log(documen t.getElementById('content')。style.color);

#content {background-color:#000000;显示:inline-block; height:100px; width:100px;}

< div id =content style =color:red;>< / div>

b
$ b console.log(document.getElementById('content')。style.backgroundColor);

没有返回任何内容



console.log(document.getElementById('content')。style.color);

返回红色

解决方案

您需要使用 getComputedStyle()来获取通过样式表分配的样式。



  console.log(getComputedStyle(document.getElementById('content'))。backgroundColor); console.log(document.getElementById('content')。style.color);  

#content {background-color:#000000;显示:inline-block; height:100px; width:100px;}

< div id =content style =color:red;>< / div>

I was looking at this post How to get the background color of an element using javascript?

which confirmed that if you do

div.style.color 

you will get returned the color applied to the div.

However this only seems to return a result if the style is applied inline on the element?

How do you return the style applied to the element when the style is applied through a style sheet (or in tags) rather than directly inline?

See example below.

console.log(document.getElementById('content').style.backgroundColor);
console.log(document.getElementById('content').style.color);

#content {
  background-color: #000000;
  display: inline-block;
  height: 100px;
  width: 100px;
}

<div id="content" style="color:red;"></div>

console.log(document.getElementById('content').style.backgroundColor);

returns nothing

console.log(document.getElementById('content').style.color);

returns red

解决方案

You need to use getComputedStyle() to get the styles assigned through the stylesheet.

console.log(getComputedStyle(document.getElementById('content')).backgroundColor);
console.log(document.getElementById('content').style.color);

#content {
  background-color: #000000;
  display: inline-block;
  height: 100px;
  width: 100px;
}

<div id="content" style="color:red;"></div>

这篇关于用JS获取当前应用样式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆