ドキュメント

Attributes/toggleClass

From jQuery JavaScript Library

Jump to: navigation, search

« Back to Attributes

toggleClass( class )

Adds the specified class if it is not present, removes the specified class if it is present.
Arguments:
classString
A CSS class to toggle on the elements.
Examples:

Toggle the class 'highlight' when a paragraph is clicked.

    $("p").click(function () {
      $(this).toggleClass("highlight");
    });

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" 
                    "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
  <script src="http://code.jquery.com/jquery-latest.js"></script>
  
  <script>
  $(document).ready(function(){
    
    $("p").click(function () {
      $(this).toggleClass("highlight");
    });

  });
  </script>
  <style>
  p { margin: 4px; font-size:16px; font-weight:bolder; 
      cursor:pointer; }
  .blue { color:blue; }
  .highlight { background:yellow; }
  </style>
</head>
<body>
  <p class="blue">Click to toggle</p>
  <p class="blue highlight">highlight</p>
  <p class="blue">on these</p>
  <p class="blue">paragraphs</p>
</body>
</html>

NameType

toggleClass( class, switch )

New in jQuery 1.3 Adds the specified class if the switch is true, removes the specified class if the switch is false.
Arguments:
classString
A CSS class to toggle on the elements.
switchBoolean
A boolean value to toggle the class by.
Examples:

Toggle the class 'highlight' on every third click.

    var count = 0;
    $("p").click(function(){
      $(this).toggleClass("highlight", count++ % 3 == 0);
    });

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" 
                    "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
  <script src="http://code.jquery.com/jquery-latest.js"></script>
  
  <script>
  $(document).ready(function(){
    
    var count = 0;
    $("p").click(function(){
      $(this).toggleClass("highlight", count++ % 3 == 0);
    });

  });
  </script>
  <style>
  p { margin: 4px; font-size:16px; font-weight:bolder; 
      cursor:pointer; }
  .blue { color:blue; }
  .highlight { background:red; }
  </style>
</head>
<body>
  <p class="blue">Click to toggle</p>
  <p class="blue highlight">highlight</p>
  <p class="blue">on these</p>
  <p class="blue">paragraphs</p>
</body>
</html>

NameType