JavaScript slidedown without jQuery

前端 未结 11 869
离开以前
离开以前 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:43

    Here's the solution to use slideDown, slideUp animation with an unknown content height element. https://jsfiddle.net/gebpjo1L/18/

    It based on the CSS 3 height animation, but the animation requires a specified content height, so you need to get the height of the content via JavaScript before you expanding it.

    var container = document.querySelector('div')
    var button    = document.querySelector('button')
    
    button.addEventListener('click', () => {
        /** Slide down. */
        if(!container.classList.contains('active')) {
            /** Show the container. */
        	container.classList.add('active')
            container.style.height = "auto"
            
            /** Get the computed height of the container. */
        	var height = container.clientHeight + "px"
    
            /** Set the height of the content as 0px, */
            /** so we can trigger the slide down animation. */
            container.style.height = "0px"
    
            /** Do this after the 0px has applied. */
            /** It's like a delay or something. MAGIC! */
            setTimeout(() => {
                container.style.height = height
            }, 0) 
        
    	/** Slide up. */
        } else {
        	/** Set the height as 0px to trigger the slide up animation. */
        	container.style.height = "0px"
            
            /** Remove the `active` class when the animation ends. */
        	container.addEventListener('transitionend', () => {
            	container.classList.remove('active')
            }, {once: true})
        }
    })
    div {
        transition: height .5s ease;
        overflow  : hidden;
    }
    
    div:not(.active) {
        display: none;
    }
    I'm an unknown content height element. I'm an unknown content height element. I'm an unknown content height element. I'm an unknown content height element. I'm an unknown content height element. I'm an unknown content height element. I'm an unknown content height element. I'm an unknown content height element. I'm an unknown content height element. I'm an unknown content height element. I'm an unknown content height element. I'm an unknown content height element.

提交回复
热议问题