首頁 >web前端 >css教學 >如何讓第 n 個子選擇器忽略網格佈局中的隱藏元素?

如何讓第 n 個子選擇器忽略網格佈局中的隱藏元素?

DDD
DDD原創
2024-11-15 15:28:03407瀏覽

How to Make nth-Child Selector Ignore Hidden Elements in a Grid Layout?

Skipping Hidden DIVs in nth-Child Selector

Problem:

When using the nth-child selector to style elements in a grid layout, hidden elements are still counted as siblings, disrupting the desired styling.

Pure CSS Solution (Not Possible):

The nth-child selector considers all siblings regardless of their visibility, so it's not possible to ignore hidden elements using only CSS.

jQuery Solution:

To solve this issue, we can use jQuery to remove hidden elements from the DOM, effectively "excluding" them from the nth-child selector's count. Here's the modified code:

<br>var divs;</p>
<p>$('.photos-board-item').each(function(i){</p>
<pre class="brush:php;toolbar:false">$(this).data('initial-index', i);

});

$('.hide-others').on('click', function () {

if(divs) {
    $(divs).appendTo('.row').each(function(){
        var oldIndex = $(this).data('initial-index');
        $('.photos-board-item').eq(oldIndex).before(this);
    });
    divs = null;
} else {
    divs = $('.css--all-photo').detach();
}

});

Explanation:

  • On page load, each item is given an initial index.
  • When the "Hide others" button is clicked:

    • If hidden divs exist, they are re-attached to the grid.
    • If no hidden divs exist, the elements with the class "css--all-photo" are detached from the grid, excluding them from the DOM and nth-child counting.

Using this jQuery-based approach, the nth-child selector only counts visible siblings, ensuring the desired grid styling regardless of which or how many divs are hidden.

以上是如何讓第 n 個子選擇器忽略網格佈局中的隱藏元素?的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn