[英]Find first element in div that has margin? (purpose: remove margin)
我需要找到一个具有CSS边距集(> 0 px)的div 中的第一个(和最后一个)元素。 (重要的是:这不一定是第一个或最后一个元素!)
基本上,我需要这样做,以便我可以删除第一个元素的margin-top和最后一个的margin-bottom。 现在我知道你可能会说“为什么不用”p:last“CSS语法?”
因为第一个或最后一个元素也可以是其他元素,它可以是列表(UL,OL),图像,段落等。我不能简单地做,ul:last,ol:last,p:last as这可能导致多个元素匹配(每种类型一个)。
我只想将它应用于单个元素。 所以这就是为什么我认为jquery是唯一的解决方案。 不过,我很乐意这么做错。
既然你只想要第一个/最后一个有边距的孩子,我想你需要使用jQuery / JavaScript:
var isfirst = 1, lastelm;
$("#divid").find("*").each(function() {
var cur = $(this);
if(parseInt(cur.css("margin-top")) > 0 && isfirst == 1) {
cur.css("margin-top", 0);
isfirst = 0;
}
if(parseInt(cur.css("margin-bottom")) > 0) {
lastelm = cur;
}
});
lastelm.css("margin-bottom", 0);
我建议在jquery(http://api.jquery.com/filter/)中使用filter方法。
这是我能想到的一个例子
<html>
<body>
<p>
<p>A<p>
<p>B<p>
<p style="margin: 10px;">C<p>
<p style="margin: 10px;">C<p>
<p>D<p>
</p>
<script>
$(document).ready(function(){
$('p').filter(function(){
return this.style.margin != '';
}).last().css('color','red');
});
</script>
<body>
您可能希望构建过滤逻辑...
:last
实际上不是jQuery之外的CSS选择器。 但你可以使用的是:first-child
以及:last-child
:
#my-element > *:first-child {
margin-top: 0;
}
#my-element > *:last-child {
margin-bottom: 0;
}
编辑:太晚了。 但是我肯定会使用>
选择器,以免在#my-element
为每个第一个孩子设置样式(比如ul
的第一个li
或p
的strong
)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.