Remove right margin on every fourth VISIBLE element using jQuery?
I have successfully used the jQuery :nth-child() selector to remove the right margin from every fourth element in a long list of div's. It looks like this:
$(".myDivClass:nth-child(4n+4)").css("margin-right", 0);
But the page is also open for user interaction (via jQuery) and one of the things that the user can do is hide/show elements. When an element is hidden, its style is set to "display:none". The elements are 开发者_运维百科floated so if you remove one element in the middle of a row, an element from the row below will jump up, like this:
My first thought was to redo the whole thing by first adding a margin to all elements and then remove it from every fourth visible element; something like this:
$(".myDivClass").css("margin-right","20px");
$(".myDivClass:visible:nth-child(4n+4").css("margin-right", 0);
But the second row does nothing and I don't think you can stack pseudo selectors like in the example above(?)
Is there a solution to this problem? Is there a better way to do this?
Thanks in advance!
/Thomas
I know this isn't directly an answer to your question, but when I do similar things with floating a bunch of block elements with some spacing between them, I usually will keep the margin on all of them but make their parent container have (in this case) a negative margin-right equal to the spacing between the elements.
This way the parent will still fit where you want it but the children will just float as they should with the space they need.
Hmm, ok the nth-child()
selector seems to not function as it should. It seems to ignore the hidden elements. So you may have to .remove()
or .detach()
the closed elements. Here is a demo, but it modifies the border instead of the margin to make it more visible for demo purposes.
$('.box:visible:nth-child(5n+5)').addClass('noSide');
$('.close').click(function() {
// needs to be removed or detached because the nth child
// appears to ignore hidden elements
$(this).parent().detach();
$('.noSide').removeClass('noSide');
$('.box:visible:nth-child(5n+5)').addClass('noSide');
});
精彩评论