jQuery: Toggling between 3 classes (initially)

后端 未结 8 547
你的背包
你的背包 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: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;
    }
    
    
    Toggle classes
    
    look at me!

提交回复
热议问题