简体   繁体   中英

How can I implement a toggle on an element to change CSS with jQuery?

I have the following html:

<a id="page-width" href="#" class="button">
    <div class="icon sprite-application-text" ></div>
</a>

How can I make it so that when the link is clicked:

  1. the class changes to <div class="icon sprite-application-sidebar-list.png" >
  2. the object with <section id="menu" class="grid_3"></section> has a width of 0%
  3. the object with <section id="content" class="grid_9"></section> changes to a class of "grid_12"

and then when it is clicked again the class changes back to:

  1. <div class="icon sprite-application-text" >
  2. the object with <section id="menu" class="grid_3"></section> has a width of 23%
  3. the object with <section id="content" class="grid_9"></section> changes to a class of "grid_9"

I need some kind of toggle action but I am not sure how to implement this with jQuery?

You should look at the toggleClass() api of jQuery.

You can easily toggle the class using that. Also, for changing the width you can define it in some css class, so that the desired width is set when you toggle it.

$(".icon sprite-application-text").removeClass("icon
sprite-application-text").addClass("icon
sprite-application-sidebar-list.png");

$(".icon sprite-application-sidebar-list.png").removeClass("icon
sprite-application-sidebar-list.png").addClass("icon
sprite-application-text");
if ($("#menu").width() == 0) 
{
   $("#menu").width("23%");
   $("#content").removeClass("grid-9").addClass("grid-12");
}
else
{
   $("#menu").width("0");
   $("#content").removeClass("grid-12").addClass("grid-9");
}

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