简体   繁体   中英

Conditionals for several CSS elements

I have a CSS file that was originally embedded within a JavaScript file, so conditionals could be created by combining the CSS embedded style sheet with JavaScript logic. I am now in the process of separating the CSS and JavaScript files and have problems dealing with the larger chunks of CSS affected by a single conditional.

I know one solution is to create a conditional within the JavaScript/JQuery code that will handle the style changes:

if(condition == true) {
      $(".element").css("left", "360px");
}

That seems like an okay solution for CSS styles that have only a couple of changing attributes. However, in my case I would have to write 100~ lines of code just for the if else statement. Is there a more intuitive way to do this task?

Perhaps you could add a class to a parent like <body>

if(condition == true) {
      $('body').addClass('conditional-class');
}

And add specific rules in css:

.conditional-class .element{
   top: 360px;
}

You could use objects to keep css, needed for some condition. For example:

 const firstCondition = { outline: '1px solid red', backgroundColor: 'blue', color: 'white' }; const secondCondition = { outline: '1px solid blue', backgroundColor: 'red', color: 'yellow' }; function applyStyles(node, styles){ Object.keys(styles).forEach((key) => { node.style[key] = styles[key]; }); } let counter = 0; const target = document.querySelector("#target"); function switchStyles(){ if(counter % 2 === 0){ applyStyles(target, firstCondition); }else if(counter % 2 === 1){ applyStyles(target, secondCondition); } counter++; } 
 <div> <div id="target"> Hello! </div> <button onClick="switchStyles()">Switch style</button> </div> 

For further learning, I recommend you reading about jss

You can add a separate css file using javascript -

if(condition == true) {
  $('head').append('<link rel="stylesheet" type="text/css" href="style.css">');
} else {
  $('head').append('<link rel="stylesheet" type="text/css" href="index.css">');
}

short and simple, yet effective in your case.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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