Set parent style via child [duplicate]

别说谁变了你拦得住时间么 提交于 2021-01-28 03:22:51

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!