[英]CSS - Styling div using classes in same html tag
I have a dropdown wherein when you click on the parent, it gets displayed. 我有一个下拉菜单,当您单击父菜单时,它会显示出来。
HTML 的HTML
<div class="dropdown"></div>
To do this I am using jQuery to add a class ( .active
) to the html. 为此,我使用jQuery向html添加一个类(
.active
)。
JS/jQuery JS / jQuery
if ($(e).children('.dropdown').hasClass('active')) {
$(e).children('.dropdown').removeClass('active');
return;
}
$('.dropdown').removeClass('active');
$(e).children('.dropdown').addClass('active');
return;
While writing this, I encountered a problem which could occur. 在撰写本文时,我遇到了可能发生的问题。
Having the CSS code look like this: 使CSS代码如下所示:
.dropdown{
/*dropdown styles*/
}
.active{
/*active styles*/
}
Leaves the possibility if I use .active
for another tag, the two styles could clash. 如果将
.active
用于另一个标签,则两种样式可能会发生冲突。
I quickly learned that 我很快了解到
.dropdown .active{
/*active styles*/
}
does not work as .active
is not the child of .dropdown
不起作用,因为
.active
不是.active
的子.dropdown
Thus one of the solutions I found was: 因此,我发现的解决方案之一是:
.parent .active{
/*active styles*/
}
However, if say that .parent
class has another child which changes styles when clicked (which needs to be styled searately), applying .active
to it would give the dropdown .active
styles. 但是,如果说
.parent
类有另一个子级,则该.parent
级在单击时会更改样式(需要按风格进行样式化),对其应用.active
会产生下拉式.active
样式。 If that was a little confusing, see this example: 如果这有点令人困惑,请参见以下示例:
.parent{
/*parent styles*/
}
.dropdown{
/*dropdown styles*/
}
.active{
/*DROPDOWN active styles*/
}
.click-me-button{
/*default button to be clicked so as to be restyled*/
}
(hopefully that makes sense) (希望这是有道理的)
I've found two solutions for this: 我已经找到了两种解决方案:
1) name each .active
something unique, like .dropdown-active
and .click-me-button-active
; 1)为每个
.active
命名一个独特的名称,例如.dropdown-active
和.dropdown-active
.click-me-button-active
; however, I am against using this as that requires more typing (call me lazy if you will) 但是,我反对使用它,因为这需要更多的输入(如果愿意,请叫我懒惰)
2) use .dropdown[class="dropdown active"]
; 2)使用
.dropdown[class="dropdown active"]
; however, this will break if the <div>
looks like this: 但是,如果
<div>
如下所示,这将中断:
<div class="dropdown blue active">
or 要么
<div class="dropdown active blue">
To overcome both of this I've found the following: 为了克服这两个问题,我发现了以下几点:
`.dropdown[class*="active"]` or `.dropdown[class~="active"]`
they both seem to work the same. 他们似乎都一样工作。
What I am trying to figure out with this question is: what is correct way to do this and what will be the best preformance-wise choice, of ANY of the above 我要解决的问题是:什么是正确的方法?什么是上述任何方面的最佳性能选择?
I think you're looking to do something like: 我认为您正在寻找类似的方法:
.dropdown.active {
text-decoration:underline;
}
Note the lack of space between .dropdown
and .active
. 注意
.dropdown
和.active
之间没有空格。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.