JavaScript slidedown without jQuery

前端 未结 11 968
离开以前
离开以前 2020-11-27 14:03

I wish to have a similar effect to jQuery slidedown but without using jQuery or any other libary. I know it\'s \"possible\" as anything in jQuery can be don

11条回答
  •  粉色の甜心
    2020-11-27 14:40

    Since we are in 2014, why not use CSS transitions and just change the height property of the element? Fiddle

    CSS:

    .wrapper {
        transition:height 1s ease-out;
        height:0;
        overflow:hidden;
    }
    

    HTML:

    //content

    JAVASCRIPT:

    document.getElementById("wrapper").style.height = //content height +"px";
    

    2020 EDIT (dealing with unknown height):

    So we're in 2020 and it's even more obvious now we should rely on CSS effects for this kind of animations.

    However, a valid point has been made against this answer - you need to specify the height of the element that you're animating in the js code, and you might not know this value in advance.

    So six years later, I'm adding a couple extra lines of code to cover this case.

    So if we use the same CSS and HTML as in our old 2014 example, this is the new JS. New Fiddle!

    const slideDown = elem => elem.style.height = `${elem.scrollHeight}px`;
    
    slideDown(document.getElementById("wrapper"));
    
    

提交回复
热议问题