javascript - 动态运行 jQuery 代码(如果我的主体添加 div 类)

标签 javascript jquery

我的正文选择器动态添加了新类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<= 4 个 child 使用 jQuery:

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;
}

关于javascript - 动态运行 jQuery 代码(如果我的主体添加 div 类),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52111454/

相关文章:

javascript - 根据当前页面以不同颜色突出显示主菜单中的链接

javascript - 使用 THIS 选择当前元素的特定子元素

javascript - jquery mobile - loadPage 问题

jquery - .click() 子 radio 触发器 : Uncaught RangeError: Maximum call stack size exceeded

Javascript-嵌套标签列表

javascript - 导入对象时出错 : SyntaxError: Unexpected token {

javascript - 奇怪的链接到/未定义 AngularJS

jquery - Msdropdown - 通过函数创建 - 附加 onchange 事件

javascript - Jasmine中 "it()"代表什么?

javascript - 为 React App 开发一个 Redux store 作为一个单独的 NPM 模块