gpt4 book ai didi

jquery - CSS从多个具有相同类的目标中定位正确的div

转载 作者:太空宇宙 更新时间:2023-11-04 10:51:20 24 4
gpt4 key购买 nike

我正在尝试删除一个 margin-top 到一个 div 中的一个段落,只有当整个 div 的高度大于 138px 时。

问题是我有多个具有相同类的 div,其中一些的高度大于 138 而另一些则没有。

现在,当其中一个高于 138px 时,我的 jQuery 添加了 margin-top: 0;到每个 div.llamada > p

我怎样才能只定位正确的 .llamada p 而不是其他的?我的代码:

HTML

<div class="call llamada">
<p style="margin-top: 0px;">This is the box number one with height bigger than 138px (correct style).</p>
</div>
<div class="call llamada" style="margin-top: 0px;">
<p style="margin-top: 0px;">This is the box number two with height lower than 138px (incorrect style).</p>
</div>

jQuery

    jQuery(document).ready(function($) {
$('.llamada').each(function(){
var heightllamada = $(".llamada").outerHeight()

if (heightllamada > 138){
$(".llamada p").css('margin-top',0);
}
});
});

谢谢!!

最佳答案

您应该将 jQuery 代码更改为以下内容:

jQuery(document).ready(function($) {
$('.llamada').each(function(){
var heightllamada = $(this).outerHeight()

if (heightllamada > 138){
$(".llamada p").css('margin-top',0);
}
});
});

你错在.each()里面获取 heightllamada 时的功能.

在你拥有 $('.llamada').outerHeight() 之前.这将通过类 llamada 遍历每个 div并获取高度,然后将最后一个 div 高度分配给您的变量。

我改成了$(this).outerHeight() .使用 this将获取当前在循环中的元素。您还可以修改您的 .each()像这样:

$('.llamada').each(function(index, element) {

然后使用$(element).outerHeight()

编辑:

您还需要更改这一行:

$(".llamada p").css('margin-top',0);

对此:

$(this).children('p').css('margin-top',0);

这个和上面的原因一样,需要用this . .children()用于选择子元素(在本例中为 <p> )

关于jquery - CSS从多个具有相同类的目标中定位正确的div,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34975656/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com