Using JQuery to toggle div visibility

前端 未结 4 1825
粉色の甜心
粉色の甜心 2021-01-12 13:10

I\'m writing some jquery code to toggle a Div visibility. I followed the method posted here: http://jsfiddle.net/Ga7Jv/.

When the user clicks an image (next to a H2

相关标签:
4条回答
  • 2021-01-12 13:37

    Problem with your code is that its last function call is .hide(), thus it will always hide the div

    Simply use .toggle(), it display or hide the matched elements.

    $(function(){
        $('.expander').live('click',function(){
            $('#TableData').toggle();
        });
    });
    

    Fiddle

    OR

    $(function () {
        $('.expander').live('click', function () {
            $('#TableData').slideToggle();
        });
    });
    

    Fiddle with slide

    You can use .slideToggle(), if you want to display or hide the matched elements with a sliding motion

    0 讨论(0)
  • 2021-01-12 13:44

    This fiddle demonstrate how to toggle a div inside the div.

    Toggle div inside the div

    $('.toggle').click(function(){ $('.showMe').slideToggle('slow'); });

    0 讨论(0)
  • 2021-01-12 13:51

    Inside your function it shows the div and then hide it again.

    You can alternate its state by calling .toggle() function, so jQuery decides to show or to hide it by itself.

    0 讨论(0)
  • 2021-01-12 13:54

    If you want to switch class names in the same element, better to have one another fixed class in it and keep changing the other ones.

    here is what I am saying:

    $(function(){
        $(".toggler").on("click", function(){
            $(this)
            .toggleClass("expander expanded")
            .parent().next().slideToggle();
        });
    });
    

    TIP:

    • Here .toggler is the fixed class for the trigger element and I am switching .expander and .expanded classes in it.

    • Also, you are selecting wrong element for slideToggle. #TableData is .parent().next().

    Working Demo : http://jsfiddle.net/ashishanexpert/nuw2M/1/

    0 讨论(0)
提交回复
热议问题