jQuery: Toggling between 3 classes (initially)

后端 未结 8 518
你的背包
你的背包 2020-11-29 09:32

I\'ve seen several posts here on SO but they are too specific in functionality and structure, and what I\'m looking for is something more universal that I or anyone can use

相关标签:
8条回答
  • 2020-11-29 10:06
    var classes = ['class1', 'class2', 'class3'],
        currentClass = 0;
    
    $('.toggle').click(function () {
    
        $('div').removeClass(classes[currentClass]);
    
        if (currentClass + 1 < classes.length)
        {
            currentClass += 1;
        }
        else
        {
            currentClass = 0;
        }
    
        $('div').addClass(classes[currentClass]);
    
    });
    

    Something like that should work OK :)

    Tinker IO link - https://tinker.io/1048b

    0 讨论(0)
  • HTML:

    <div id="example" class="red">color sample</div>
    

    CSS:

    .red {
      background-color: red;
    }
    .yellow {
      background-color: yellow;
    }
    .green {
      background-color: green;
    }
    

    JS:

    $(document).ready(function() {
        var colors = ['red', 'yellow', 'green'];
        var tmp;
        setInterval(function(){
            tmp && $('#example').removeClass(tmp);
            tmp = colors.pop();
            $('#example').addClass(tmp);
            colors.unshift(tmp);
        }, 1000);
    });
    

    DEMO

    0 讨论(0)
  • 2020-11-29 10:11

    This worked for me and I can stack as many as I want, then wrap around easily.

    switch($('div.sel_object table').attr('class'))
        {
        case "A":   $('div.sel_object table').toggleClass('A B'); break;
        case "B":   $('div.sel_object table').toggleClass('B C'); break;
        case "C":   $('div.sel_object table').toggleClass('C D'); break;
        case "D":   $('div.sel_object table').toggleClass('D A'); break;                
        }
    
    0 讨论(0)
  • 2020-11-29 10:13

    Another version that uses classList replace. Not supported by all browsers yet.

    var classes = ["class1", "class2", "class3"];
    var index = 0;
    var classList = document.querySelector("div").classList;
    const len = classes.length;
    
    $('.toggle').click(function() {
      classList.replace(classes[index++ % len], classes[index % len]);
    });
    .class1 {
      background: yellow;
    }
    
    .class2 {
      background: orange;
    }
    
    .class3 {
      background: red;
    }
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    
    <a href="#" class="toggle">Toggle classes</a>
    <div class="class1">
      look at me!
    </div>

    0 讨论(0)
  • 2020-11-29 10:15

    I converted user3353523's answer into a jQuery plugin.

    (function() {
      $.fn.rotateClass = function(cls1, cls2, cls3) {
        if ($(this).hasClass(cls1)) {
          return $(this).removeClass(cls1).addClass(cls2);
        } else if ($(this).hasClass(cls2)) {
          return $(this).removeClass(cls2).addClass(cls3);
        } else if ($(this).hasClass(cls3)) {
          return $(this).removeClass(cls3).addClass(cls1);
        } else {
          return $(this).toggleClass(cls1); // Default case.
        }
      }
    })(jQuery);
    
    $('#click-me').on('click', function(e) {
      $(this).rotateClass('cls-1', 'cls-2', 'cls-3');
    });
    #click-me {
      width: 5em;
      height: 5em;
      line-height: 5em;
      text-align: center;
      border: thin solid #777;
      margin: calc(49vh - 2.4em) auto;
      cursor: pointer;
    }
    
    .unselectable {
      -webkit-touch-callout: none;
      -webkit-user-select: none;
       -khtml-user-select: none;
         -moz-user-select: none;
          -ms-user-select: none;
              user-select: none;
    }
    
    .cls-1 { background: #FFAAAA; }
    .cls-2 { background: #AAFFAA; }
    .cls-3 { background: #AAAAFF; }
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <div id="click-me" class="unselectable">Click Me!</div>


    Dynamic Approach

    (function() {
      $.fn.rotateClass = function() {
        let $this = this,
            clsList = arguments.length > 1 ? [].slice.call(arguments) : arguments[0];
        if (clsList.length === 0) {
          return $this;
        }
        if (typeof clsList === 'string') {
          clsList = clsList.indexOf(' ') > -1 ? clsList.split(/\s+/) : [ clsList ];
        }
        if (clsList.length > 1) {
          for (let idx = 0; idx < clsList.length; idx++) {
            if ($this.hasClass(clsList[idx])) {
              let nextIdx = (idx + 1) % clsList.length,
                  nextCls = clsList.splice(nextIdx, 1);
              return $this.removeClass(clsList.join(' ')).addClass(nextCls[0]);
            }
          }
        }
        return $this.toggleClass(clsList[0]);
      }
    })(jQuery);
    
    $('#click-me').on('click', function(e) {
      $(this).rotateClass('cls-1', 'cls-2', 'cls-3');     // Parameters
      //$(this).rotateClass(['cls-1', 'cls-2', 'cls-3']); // Array
      //$(this).rotateClass('cls-1 cls-2 cls-3');         // String
    });
    #click-me {
      width: 5em;
      height: 5em;
      line-height: 5em;
      text-align: center;
      border: thin solid #777;
      margin: calc(49vh - 2.4em) auto;
      cursor: pointer;
    }
    
    .unselectable {
      -webkit-touch-callout: none;
      -webkit-user-select: none;
       -khtml-user-select: none;
         -moz-user-select: none;
          -ms-user-select: none;
              user-select: none;
    }
    
    .cls-1 { background: #FFAAAA; }
    .cls-2 { background: #AAFFAA; }
    .cls-3 { background: #AAAAFF; }
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <div id="click-me" class="unselectable">Click Me!</div>

    0 讨论(0)
  • 2020-11-29 10:23

    Cycles through the index of classes and toggles from one to ther other.

    var classes = ['border-top','border-right','border-bottom','border-left'];
    var border = 'border-top';
    var index = 0;
    var timer = setInterval( function() {
        var callback = function(response) {
            index = ( ++index == 4 ? 0 : index );
            $(element).html("text").toggleClass( border + " " + classes[index] );
            border = classes[index];
            };
        }, 1000 );
    
    0 讨论(0)
提交回复
热议问题