开发者

jQuery to hide and show divs with an indicator

开发者 https://www.devze.com 2023-02-01 04:21 出处:网络
Using the jQuery below to toggle the hiding and showing of divs of text: how would I add some sort of indicator - like an up and down arrow as a graphic - to the titles when the divs are either open a

Using the jQuery below to toggle the hiding and showing of divs of text: how would I add some sort of indicator - like an up and down arrow as a graphic - to the titles when the divs are either open and closed? What's the best way to do that? Two images? A CSS sprite? And most importantly: how would that be in开发者_JAVA百科tegrated into the JS?

I've looked at other jQuery that assigns a random number to each div and then determines which are open and which are closed and toggles one of two images. But I'm using php in a WordPress loop to show a posts, and that gives problems with incrementing in the loop, so there must be an easier way that doesn't require changes in the name of the title div. Thanks....

This JS fires the showing and hiding. Each div can be expanded and collapsed independently.

$(document).ready(function() {
  $('div.demo-show:eq(0)> div').hide();  
  $('div.demo-show:eq(0)> h3').click(function() {
    $(this).next().slideToggle('fast');
  });
});

This is the HTML it works with:

<div class="collapser">

<p class="title">Header-1 </p>
<div class="contents">Lorem ipsum</div>

<p class="title">Header-2</p>
<div class="contents">Lorem ipsum </div>

<p class="title">Header-3</p>
<div class="contents">Lorem ipsum</div>

</div>

The CSS is arbitrary:

.collapser {
margin: 0;
padding: 0;
width: 500px;
}

.title {
margin: 1px;
color: #fff;
padding: 3px 10px;
cursor: pointer;
position: relative;
background-color:#c30;
}

.contents {
padding: 5px 10px;
background-color:#fafafa;
}


You could use the toggleClass method to set the class on the click handler. to either up or down. Each class would have the appropriate background image set.

In your click handler

$('.collapser').toggleClass('up down');

and your html would look like this

<div class="collapser up">
</div>
0

精彩评论

暂无评论...
验证码 换一张
取 消