简体   繁体   中英

CSS collapse/expand div

<style>
    .faq ul li {
        display: block;
        float: left;
        padding: 5px;
    }

    .faq ul li div {
        display: none;
    }

    .faq ul li div:target {
        display: block;
    }
</style>
<div class="faq">
    <ul>
        <li><a href="#question1">Question 1</a>
            <div id="question1">Answer 1 </div>
        </li>
        <li><a href="#question2">Question 2</a>
            <div id="question2">Answer 2 </div>
        </li>
        <li><a href="#question3">Question 3</a>
            <div id="question3">Answer 3 </div>
        </li>
        <li><a href="#question4">Question 4</a>
            <div id="question4">Answer 4 </div>
        </li>
        <li><a href="#question5">Question 5</a>
            <div id="question5">Answer 5 </div>
        </li>
        <li><a href="#question6">Question 6</a>
            <div id="question6">Answer 6 </div>
        </li>
    </ul>
</div>

I found this great link http://jsfiddle.net/ionko22/4sKD3/ regarding collapsible div using CSS. Is there a way to have question 1 always open without clicking on it when you visit the page. And make it collapse when you click on any other questions. Also is there a way to close the div/questions by clicking on itself? I would be very grateful if you can reply to this.

http://jsfiddle.net/4sKD3/821/

Add this to the CSS to make the first question appear by default:

.faq ul li:first-of-type div {
    display: block;
}

And add this jQuery for toggling:

$(".faq ul li").click(function() {
    if( $( this ).children( "div" ).css( "display" ) == "none" ) {
        $( ".faq ul li div" ).hide();
        $( this ).children( "div" ).show();
    } else {
        $( ".faq ul li div" ).hide();
    }
});

I've been playing with this for a good two hours now using first-child , .current , :not syntax and a variety of class combinations. I think it's safe to say that displaying the first div to begin with, then having it disappear when another is the :target isn't possible with just pure CSS and HTML.

I got it to the point where the first question was display: block; , and all the others were going on and off when another was active, however the first question was always active throughout.

So, in answer to your question:

No, I am 95% sure it is not possible with the markup above, as each div is in its own individual li . I was hoping I could prove myself wrong, but I cannot. If someone else can achieve this then they'll certainly be getting an up-vote from me.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM