动态地使用 jQuery 代码(如果我的body添加了 div 类)



我的身体选择器动态添加了新的类st--sticky-header。(滚动后(

我制作了一个jQuery代码,这在控制台浏览器中工作,但该代码只能静态工作。我希望我的代码动态运行,如果我的体类st--sticky-header将动态添加。

$('.filter--facet-container').each(function () {
if ($(this).children().length <= 5) {
$(".action--filter-btn").css("display", "none");
$(".action--sort.action--content.block").css("margin-bottom", "10px");
}
if ($(this).children().length <= 4) {
$(".filter--container-additional").css({
paddingBottom: "20px",
height: "125px"
});
// this code - start
if ($("body").hasClass("st--sticky-header")) {
$(".filter--container-additional").css({
height: "100px"
});
}
else {
$(".filter--container-additional").css({
height: "125px"
});
}
// this code - end
}
});

你可以在不使用jQuery的情况下实现所有这些,因为你只是在修改CSS。通过将body添加到选择器中,我们使其更加具体,因此它将覆盖以前的定义.filter--container-additional.

只需将以下内容添加到您的 CSS 中:

.filter--container-additional {
height: 125px;
}
body.st--sticky-header .filter--container-additional {
height: 100px;
}

除了您的评论之外,如果.filter--facet-container使用 jQuery 有 4 个孩子<=,您可以添加另一个类:

if( $('.filter--facet-container').children() <= 4 )
{
$('body').addClass('four-or-less');
}

然后进一步更新您的 CSS,如下所示:

body.four-or-less .filter--container-additional {
height: 125px;
}
body.four-or-less.st--sticky-header .filter--container-additional {
height: 100px;
}

最新更新