问题
Let's say I have the following <ul>
:
<ul>
<li>Child</li>
<li><span class="active">Child</span></li>
<li>Child</li>
</ul>
Is it possible for me to change the style of the <li>
via the active
<span>
?
E.g.:
.active:parent(li) {
background-color: red;
}
I've been able to achieve this with jQuery, but it flickers on the screen for a split second (waiting for the DOM to load) and I want to avoid that.
回答1:
There's no way to do this in CSS.
The best thing to do would be to do something like:
<ul class="has-active">
<li>Child</li>
<li><span class="active">Child</span></li>
<li>Child</li>
</ul>
And style
ul.has-active {
...
}
If you are looking for something that can do parent selectors, then look at something like xpath.
回答2:
This is impossible with pure CSS because it can't go backwards.
You must use Javascript or jQuery:
$(document).ready(function(){
$('li').has('.active').css('background-color','yellow');
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<ul>
<li>Child</li>
<li><span class="active">Child</span></li>
<li>Child</li>
</ul>
来源:https://stackoverflow.com/questions/48676386/set-parent-style-via-child