简体   繁体   中英

How do I minimize a div and hide containing divs?

So currently, I have jQuery in a function that reduces a div to 20px when a certain toggle button is clicked. I want all the divs inside of that div to hide as well, but I don't want to resort to recursive functions/loops if at all possible. Currently, my toggle button kind of works, but when I hide a div all of its children (if it has any) remain where they were before. Can I simply force the height to 20px and make all the containing divs disappear as well? A good example of what I need would be like hiding a comment chain on a board (such as reddit). Thanks.

Sure, code:

function toggleComment(child)
{
    if (child.innerHTML.includes("–"))
    {
        //Minimizing
        child.innerHTML = "[+]";
        $(child).parent().addClass("minimized");
        hideChildren($(child).parent());
    }
    else
    {
        //Maximizing
        child.innerHTML = "[–]";
        $(child).parent().removeClass("minimized");
        showChildren($(child).parent());
    }
}

function hideChildren(parent)
{
    for (var i = 0; i < parent.children().length; i++)
    {
        var child = parent.children().eq(i);
        if (!child.hasClass('ignoreOnHide'))
        {
            parent.children().eq(i).hide();
        }            
        if (child.has("div"))
        {
            hideChildren(child);
        }
    }
}

function showChildren(parent)
{
    for (var i = 0; i < parent.children().length; i++)
    {
        var child = parent.children().eq(i);
        parent.children().eq(i).show();
    }
}

This code partially works. It visually functions as intended, but there become more complicated problems. I would like to not use recursive functions and loops, because, again, it doesn't work exactly as intended. The exact problems are difficult to explain and not pertinent to this question. Is there any other way to go about this problem, to minimize a div and completely hide its content, without loops & such?

Try adding

overflow: hidden;

to your parent div to hide the elements positioned outside its width/height.

You can use the CSS property 'overflow' such that the content of the div will be clipped.

.my_div { overflow: hidden; }

Playing with transitions, you may also hide the content using the 'opacity' style:

.my_div > * { opacity: 1; transition: opacity 2s ease; }
.my_div.reduced > * { opacity: 0; }

This will fade the content smoothly.

使用jQuery隐藏容器的子代:

$('div.container div').fadeOut();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM