What code do i need to collapse a div when another is open?

安稳与你 提交于 2019-12-01 20:29:16

If you were willing to use jQuery, the selector of your interest is something along the lines of

$('div#parent-container > div').filter(':visible');

For example, if I were to demonstrate with next & previous, I would do it something like this. With targeted links it would work by appending ID's to the divs and referencing those in the href attribute of `anchors'. (now included within example)


Something to mess with:

$(function(){
    //Reference Object
    var $divs = $('div > div');
    //Buffer for selected variable
    var $selected = 0;
    //Show first
    $divs.eq(0).show();


    $('#next').click(function(){
        //Update selected var
         $selected = $divs.filter(':visible');
        //Save next to variable
        var $next = $selected.next();
        //Change Visibility
        toggle($next);
        //Prevent Default
        return false;
    });

     $('#prev').click(function(){
        $selected = $divs.filter(':visible');
        var $prev = $selected.prev();
        toggle($prev);
        return false;
    });

    $('a').click(function(){
        $selected = $divs.filter(':visible');
        var selector = $(this).attr('href');
        if(selector == '#') return false;
        toggle( $( selector ) );
        return false;
    });


    var toggle = function($toggle){
     if(!$toggle.length) return false;
         $selected.hide();
         $toggle.show();   
     }
});

<!--Simple Implementation and dependancies-->
<a id="prev" href="#">Prev</a>
<a id="next" href="#">Next</a>
<a href="#item-4">Show Item Four</a>

<div>
    <div id="item-1">One</div>
    <div id="item-2">Two</div>
    <div id="item-3">Three</div>
    <div id="item-4">Four</div>
    <div id="item-5">Five</div
    <div id="item-6">Six</div>
</div>

div > div {
 font-size:5em;
 width:auto;
 text-align:center;
 padding:20px 0;   
 display:none;
}

This is something jQuery works really well for. Here is a working example in jsfiddle.

http://jsfiddle.net/mrtsherman/uqnZE/

Example html

<div class="category">A
    <div class="artists">Apple<br/>Ace<br/>Ants<br/></div>
</div>
<div class="category">B
    <div class="artists">Bee<br/>Bop<br/>Book<br/></div>
</div>
<div class="category">C
    <div class="artists">Cake<br/>Chimp<br/>Charles<br/></div>
</div>

And the code:

$(".category").click( function() {    
    $(".artists").hide();
    $(this).children(".artists").show();
});

Basically what it does is hide all the divs that contain artists, then shows the div for the one you clicked on. Really simple.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!