简体   繁体   English

在两个或多个功能之间切换

[英]Toggle between two or more functions

The following code doesn't seem to work for jQuery versions higher than 1.8. 以下代码似乎不适用于高于1.8的jQuery版本。 Can someone explain how can we get the same functionality from newer versions, though? 有人可以解释一下如何从较新的版本中获得相同的功能吗? Also, shouldn't we have a structure like element.click(function(){element.toggle();}) ? 另外,我们是否应该不具有element.click(function(){element.toggle();})这样的结构 Why is the toggle() method alone working on click, without actually specifying a .click() method before it? 为什么在单独的click上使用toggle()方法,而没有在其之前实际指定.click()方法呢?

HTML: HTML:

<div style="width: 100px; height: 100px; background: orange;"></div>

JS JS

$("div").toggle(
  function () {
    $(this).css({"background":"blue"});
  },
  function () {
    $(this).css({"background":"red"});
  },
  function () {
    $(this).css({"background":"yellow"});
  }
);

try this 尝试这个

 var count = 0; function changeBackground() { var color = ""; switch (count % 3) { case 0: color = "blue"; break; case 1: color = "red"; break; case 2: color = "yellow"; break; } $("#content").css("background", color); count++; } 
 div { height: 100px; width: 100px; background: orange; } 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> <div id="content" onclick="changeBackground()"></div> 

First of all, don't try to deal with raw CSS properties, this is really inflexible approach. 首先,不要尝试处理原始CSS属性,这确实是不灵活的方法。 Avoid $.fn.css method for styling. 避免使用$.fn.css方法进行样式设置。 You should use classes with necessary styles, background, color, etc. 您应该使用具有必要样式,背景,颜色等的类。

Now, the simple and effective solution I can think of is to use toggleClass method like this: 现在,我能想到的简单有效的解决方案是使用toggleClass方法,如下所示:

var classes = ['blue', 'red', 'yellow'];

$("div").toggleClass(function(i, oldClass) {
    var newClass = classes[(classes.indexOf(oldClass) + 1) % classes.length]
    return oldClass + ' ' + newClass;
});

Here is a simple demo that toggles classes on each click. 这是一个简单的演示,可在每次单击时切换类。

 $('.toggle').click(function() { var classes = ['blue', 'red', 'yellow']; $("div").toggleClass(function(i, oldClass) { var newClass = classes[(classes.indexOf(oldClass) + 1) % classes.length] return oldClass + ' ' + newClass; }); }); 
 div {padding: 20px; border: 1px #DDD solid;} .blue {background: blue;} .red {background: red;} .yellow {background: yellow;} 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div></div> <button class="toggle">Toggle</button> 

The benefit here is that you can toggle as many classes (not only 3) as you wich, just add new class to classes array. 这样做的好处是您可以根据需要切换任意多个类(不仅是3个),只需将新类添加到classes数组即可。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM