Javascript按类选择元素,更改其最大高度,然后更改单击元素max-height

时间:2016-02-07 19:17:23

标签: javascript jquery html css

因此,在点击时点击打开的每个元素上,我希望所有其他元素都使用该类将其最大高度设置为40px,并将点击的div最大高度设置为500px,以便我尝试做一些像acordeon的东西。所以使用Jquery这可以工作,但如何在Vanilla JS中实现它。

 <script>
            $(document).ready(function(){
                $('.click-to-open').on('click', function(){
                    if($(this).css('max-height') == '40px'){    
                        $('.click-to-open').css('max-height', '40px');
                        $(this).css('max-height', '500px');
                    }
                    else{
                        $('.click-to-open').css('max-height', '40px');
                    }
                });             
            });
        </script>

这个js脚本有效但是语句似乎不起作用 Javascript脚本:

(function(){
                var elements = document.querySelectorAll('.click-to-open');
                for(var i = 0; i < elements.length; i++){
                    elements[i].addEventListener('click',setMaxHeight);
                }

                function setMaxHeight(){
                    for(var i = 0;i < elements.length; i++){
                        elements[i].style.maxHeight = '40px';
                    }
                    if(this.style.maxHeight == '40px'){                     
                        this.style.maxHeight = '500px';
                    }
                    else {
                        this.style.maxHeight = '40px';
                    }
                }

            })();

1 个答案:

答案 0 :(得分:1)

(function(){
    var elements = document.querySelectorAll('.click-to-open');
    for(var i = 0; i < elements.length; i++){
        //Add eventlistener to all elements and check height on click
        elements[i].addEventListener('click',checkMaxHeight);
    }

    function checkMaxHeight(){
        //Set maxheight on all elements to 40px
        for(var i = 0;i < elements.length; i++){
            setMaxHeight(elements[i],40);
        }
        //Check if clicked element has maxheight 40px
        if(this.style.maxHeight == '40px'){
            //Set max height on clicked element to 500px
            setMaxHeight(this,500)
        }
    }

    function setMaxHeight(element,value){
        element.style.maxHeight = value + 'px';
    }
})();