Destroy or recalculate CSS nth-child selector

大兔子大兔子 提交于 2019-12-12 11:11:54

问题


Context:

I have a list. Using jQuery, I'm dynamically...

  1. ...hiding/showing certain list-items.
  2. ...calculating the the third and fourth list-items to apply specific classes.

Problem:

A CSS style (from a stylesheet), using an nth-child selector, is being applied to every third list item. The problem is that when I dynamically hide/show list items, the CSS nth-child selector doesn't seem to be recalculating.

Since jQuery is already calculating the third list item, I don't need to recalculate the CSS nth-child selector unless there is no means of cancelling it out or destroying it.

Code:

The mark-up:

<ul class="teamlist">
    <li>Content</li>
    <li>Content</li>
    <li>Content</li>
    <li>Content</li>
    <li>Content</li>
    <li>Content</li>
    <li>Content</li>
    <li>Content</li>
    <li>Content</li>
    <li>Content</li>
</ul>

The jQuery:

$('.teamlist li:visible').each(function (i) {
    if (i % 3 == 0) $(this).addClass('teamlist_fourth_item');
});
$('.teamlist li:visible').each(function (i) {
   if ((i+1) % 3 == 0) $(this).addClass('teamlist_third_item');
});

The unwanted CSS:

.teamlist li:nth-child(3n+3) {
    margin-right: 0;
}

Question:

How do I destroy or force the recalculation of CSS nth-child selector?


回答1:


After the comments i think what you need is to override that class to make it just equal with the properties for all li elements, you can make your own class that match those elements with a better level of specificity, for example with the id or class of the parent ul:

#parent .teamlist li:nth-child(3n+3) {
    margin-right:2%;
}

Or with an id on your ul

<ul class="teamlist" id="lista">

#lista.teamlist li:nth-child(3n+3) {
    margin-right:2%;
}

Also try to be sure your CSS is loaded after the other one

Other way you can work with Jquery too and modify this with the same CSS selector:

$('.teamlist li:nth-child(3n+3)').css('margin-right','2%');


来源:https://stackoverflow.com/questions/20336437/destroy-or-recalculate-css-nth-child-selector

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