Include CSS styles in JS variables?

I am trying to create vars for some styles that I want and reuse, but cannot make it work. What am I doing wrong?

var bgColor = "'background' : 'rgb(102,204,0)'";
var textColor = "'color' : 'rgb(40,40,40)'";  

$('.className').css({bgColor, textColor});
+4
source share
4 answers

Having looked at the docs on jquery css , if you want to apply these values ​​in one call, you will need to create a valid json, According to the docs:

var validValues = 
{ 
  "background-color": "#ffe", 
  "border-left": "5px solid #ccc" 
};

or

var validValues = 
{
  backgroundColor: "#ffe", 
  borderLeft: "5px solid #ccc" 
} 

then

$(selector).css(validValues);

Note that with DOM notes, quotation marks around property names are optional, but with a CSS notation, they are required due to a hyphen in the name

in particular, the reason your work is not working is the following: the correct json for jquery is not created:

var bgColor = "'background' : 'rgb(102,204,0)'";
var textColor = "'color' : 'rgb(40,40,40)'";  

var json = {bgColor, textColor};

json =

{
  bgColor: "'background' : 'rgb(102,204,0)'", 
  textColor: "'color' : 'rgb(40,40,40)'"
}
+3

Try:

var bgColor = "rgb(102, 204, 0)";
var textColor =  "rgb(40, 40, 40)";

$('.className').css({ "background" : bgColor, "color" : textColor });

, ​​ JSON:

var styleJson = 
{
    'background' : 'rgb(102, 204, 0)', 
    'color' : 'rgb(40, 40, 40)'
}

$('.className').css(styleJson)
+1

css style jquery.

To use it through js variables, you can convert it as an array.

var bgColor = ['background','rgb(102,204,0)'];
var textColor = ['color' , 'rgb(40,40,40)'];  


$('.className').css(bgColor[0], bgColor[1]);
$('.className').css(textColor[0], textColor[1]);

Example: http://jsfiddle.net/49byztbx/

0
source

You can also try this.

var styles = {'background-color':'rgb(102,204,0)', 'color':'rgb(40,40,40)'}
$('.className').css(styles);
0
source

Source: https://habr.com/ru/post/1616253/


All Articles