使用 jQuery 删除每四个可见元素的右边距?
我已成功使用 jQuery :nth-child() 选择器删除右侧长长的 div 列表中每第四个元素的边距。它看起来像这样:
$(".myDivClass:nth-child(4n+4)").css("margin-right", 0);
但该页面也开放供用户交互(通过 jQuery),并且用户可以做的事情之一是隐藏/显示元素。当元素隐藏时,其样式设置为“display:none”。这些元素是浮动的,因此如果您删除一行中间的一个元素,下面一行的一个元素将会向上跳跃,如下所示:
我的第一个想法是重做整个事情,首先向所有元素添加边距,然后从每四个可见元素中删除它;像这样的东西:
$(".myDivClass").css("margin-right","20px");
$(".myDivClass:visible:nth-child(4n+4").css("margin-right", 0);
但是第二行什么都不做,我认为你不能像上面的例子那样堆叠伪选择器(?)
这个问题有解决方案吗?有更好的方法吗?
提前致谢!
/托马斯
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
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我知道这并不能直接回答你的问题,但是当我做类似的事情,浮动一堆块元素之间有一定的间距时,我通常会保留所有元素的边距,但让它们的父容器有(在在这种情况下)负的 margin-right 等于元素之间的间距。
这样,父级仍将适合您想要的位置,但子级将按照其所需的空间浮动。
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.
嗯,好吧,
nth-child()
选择器似乎没有发挥应有的作用。它似乎忽略了隐藏的元素。因此,您可能必须.remove()
或.detach()
关闭的元素。这是一个演示,但它修改了边框而不是边距,以使其在演示目的时更加明显。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.