简体   繁体   English

将CSS值存储在JavaScript变量中

[英]Store CSS value in JavaScript variable

My CSS 我的CSS

.h1-modified{
    color: green;
}

My JavaScript file 我的JavaScript文件

var h1Modified = [HERE IS SOME CODE MISSING];

I want to store the color of the html class .h1-modified in the JavaScript variable h1Modified . 我想将HTML类.h1-modified的颜色存储在JavaScript变量h1Modified

If it works alert(h1Modified); 如果工作正常, alert(h1Modified); outputs green . 输出green

PROBLEM: .h1-modified isn't assigned to any HTML element. 问题: .h1-modified未分配给任何HTML元素。 I have to access the CSS file directly. 我必须直接访问CSS文件。

So if you want to read a CSS property.. I don't think you can read it directly from CSS, but you can read it from an element that has this class 因此,如果您想读取CSS属性,则无法直接从CSS读取它,但可以从具有此类的元素读取它

const tag = document.getElementById('my_id');
const styles = window.getComputedStyle(tag);
const tagColor = style.getPropertyValue('color');

You can read more about it here: CSSStyleDeclaration . 您可以在这里阅读有关它的更多信息: CSSStyleDeclaration

Or you could just read a color from an elemenet 或者您也可以从elemenet中读取颜色

const color = document.getElementById("tag").style.color;

PS: Oh, you need to parse CSS file? PS:哦,您需要解析CSS文件吗? Well, parsers are available in any language, JavaScript is one of them. 好吧,解析器可用任何语言提供,JavaScript就是其中之一。 Take a look at JSCSSP . 看一下JSCSSP It can parse CSS files, but keep in mind that this parsed file won't necessarily be the same that is used to render the website. 它可以解析CSS文件,但请记住,此解析文件不一定与用于呈现网站的文件相同。 Or that styles found in the file will be applied to your HTML tags. 否则该文件中找到的样式将应用于您的HTML标记。

I know someone already has answered it. 我知道有人已经回答了。 But here is a Jquery version: 但是这是一个Jquery版本:

$('#id').css('color', 'blue'); //To change

to store as var: 存储为var:

var x = $('#id').css('color');  //will return the colour

reference: 参考:

http://api.jquery.com/css/ http://api.jquery.com/css/

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM