简体   繁体   English

动态地将CSS类分配给另一个类

[英]Dynamically assign CSS class to another class

Is it possible to assign properties of one CSS class to another class? 是否可以将一个CSS类的属性分配给另一个类? If it can not be done with CSS, I can use server-side scripting to pass variables. 如果无法使用CSS,我可以使用服务器端脚本来传递变量。

For example, if I have a list of classes from .myclass1 to .myclass20 and I know that for user7 I need to replace .myDefault with myClass7, how can I do that? 例如,如果我有一个从.myclass1到.myclass20的类列表,我知道对于user7,我需要用myClass7替换.myDefault,我该怎么做?

In jQuery you could this code: 在jQuery中,您可以使用以下代码:

$('.myDefault').addClass('myClass7');
$('.myClass7').removeClass('myDefault');

You want all properties in a class to be inherited by another class in CSS. 您希望类中的所有属性都可以由CSS中的另一个类继承。

Not for both classes to be applied on an object dynamically by JS. 不是由JS动态地将两个类应用于对象。

That can't be done directly with CSS and a JS approach would consume quite a bit of time for you to implement. 这不能直接用CSS完成,JS方法会耗费相当多的时间来实现。

Best choice is for you to look into less css . 最好的选择是让你看看更少的CSS

It does what you want, either server side or clientside. 它可以满足您的需求,无论是服务器端还是客户端。

This isn't a direct answer, but if you want a mix of settings you can use multiple classes: 这不是一个直接的答案,但如果你想要混合设置,你可以使用多个类:

bigFont{
  font-size:150%;
}
errorBox{
  border:4px dashed red;
}
typMessage{
  padding:2px;
  margin:1px;
  overflow-y:auto;
}


<div class="typMessage">Hello World</div>

by adding the "errorBox" and/or "bigFont" class to the element it will "merge" the CSS properties. 通过向元素添加“errorBox”和/或“bigFont”类,它将“合并”CSS属性。

Here's a simple way to swap classes without jQuery: http://jsfiddle.net/imsky/mrKHB/ 这是一种在没有jQuery的情况下交换类的简单方法: http//jsfiddle.net/imsky/mrKHB/

HTML: HTML:

<div id="test" class="big one sans phone">Hello world and </div>

CSS: CSS:

.one {background:blue;color:#fff}
.two {background:yellow;color:#000}
.sans {font-family:sans-serif}
.big {font-size:24px}
.phone:after {content:"phone!"}

JavaScript: JavaScript的:

document.getElementById("test").onclick = (function(){
this.className = this.className.replace(/\bone\b/,"two");
});

You can use PHP to handle this for you. 您可以使用PHP来为您处理此问题。 Just replace eg 只需替换例如

<div class='myDefault'></div>

with

// you should have that info stored somewhere anyway :)
$userClass = 'myClass7';

// now just echo out the right class for the user
<div class="<?php echo $userClass ?>"></div>

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

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