首页 > 解决方案 > jQuery slideDown后元素css高度返回1

问题描述

在下面的 javascript 中,以下行应该找到处于slideDown()/ 可见状态的下拉容器元素的高度。但是,当单击按钮并且下拉菜单扩展返回的高度为 1 时,它似乎正在做相反的事情(我已经通过取消注释函数末尾的行来测试这一点)。当再次单击按钮以折叠下拉列表时,高度为例如 681。为什么会这样?当单击按钮以展开下拉容器时,有没有办法在此函数中正确评估展开的高度?

$(this).next(".dropdown-container").css("height")

这是完整的javascript:

$(document).ready(function () {
    var dropdown = $(".dropdown-btn");
    var i;

    for (i = 0; i < dropdown.length; i++) {
        dropdown[i].addEventListener("click", function () {
            $(".dropdown-btn").not(this).removeClass("active");
            $(".dropdown-container").slideUp();
            $(this).toggleClass("active");
            if ($(this).hasClass("active")) {
                $(this).next(".dropdown-container").slideDown();
                if (Modernizr.mq('(max-height: 750px)') || $(this).next(".dropdown-container").css("height").replace(/px/, "") > ($(document).height() - 132 - 176)) {
                    $(".dropdown-btn").not(this).slideUp();
                }
            }
             else {
                    $(".dropdown-btn").not(this).slideDown();
            }

//$('a').text($(this).next(".dropdown-container").css("height").replace(/px/, ""));
});

标签: javascriptjquerycss

解决方案


根据上面的评论,需要在回调函数中评估高度,这是slideDown方法中的第二个选项。随着代码的移动,this逻辑也需要更新为相对于容器而不是按钮。以下是更新的代码:

if ($(this).hasClass("active")) {
    $(this).next(".dropdown-container").slideDown("slow", function() {
        // Animation complete.
        if (Modernizr.mq('(max-height: 750px)') || $(this).css("height").replace(/px/, "") > ($(document).height() - 132 - 176)) {
            $(".dropdown-btn").not($(this).prev(".dropdown-btn")).slideUp();
        }
    });
}

推荐阅读