简体   繁体   English

几个CSS元素的条件

[英]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. 我有一个最初嵌入JavaScript文件中的CSS文件,因此可以通过将CSS嵌入样式表与JavaScript逻辑结合来创建条件。 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. 我现在正在分离CSS和JavaScript文件,并且在处理受单个条件影响的较大CSS块时遇到问题。

I know one solution is to create a conditional within the JavaScript/JQuery code that will handle the style changes: 我知道一种解决方案是在JavaScript / JQuery代码中创建一个条件来处理样式更改:

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

That seems like an okay solution for CSS styles that have only a couple of changing attributes. 对于只有几个变化属性的CSS样式,这似乎是一个好的解决方案。 However, in my case I would have to write 100~ lines of code just for the if else statement. 但是,就我而言,我只需要为if else语句写100几行代码。 Is there a more intuitive way to do this task? 有没有更直观的方法来执行此任务?

Perhaps you could add a class to a parent like <body> 也许您可以将类添加到像<body>这样的父类中

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

And add specific rules in css: 并在CSS中添加特定规则:

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

You could use objects to keep css, needed for some condition. 您可以使用对象保留某些条件所需的css。 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 为了进一步学习,我建议您阅读有关jss的文章。

You can add a separate css file using javascript - 您可以使用JavaScript添加单独的CSS文件-

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. 简短,简单,但对您而言有效。

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

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