简体   繁体   中英

What is the best way to implement multiway toggle using javascript/jQuery?

I have a div that can display 3 images (in the background) each indicating the 'state' of some variable: ie, partial, full and none. For each of these states I have images: partial.gif, full.gif and none.gif (ie, these are background images of that div)

Need: Circular queue like toggling effect for changing the images in this order partial -> full -> none -> partial

So if the current image is 'partial.gif' and the user clicks the div the background image changes to the next one in the sequence ie, full.gif (and if it is currently full.gif it changes to none.gif and that to partial.gif and so on).

Naive solution: have a bunch of if/else's or switch-case and check the current one (image) and then decide based on array look up which is the next one. Is this the best way of doing it? Can I leverage jQuery's toggle function somehow?

(PS: It need not be restricted to images, but could also be for different background color sequences etc., I'd like to know what it is a good 'generic' way of doing it ie, The example may be specific for background images but if I changed part of that code for background-color or font it should still work. I don't want it to be purely generic, but just enough so it is easy to modify for other attributes. If not, that's fine too. Just a thought:)

http://api.jquery.com/toggle-event/

To be precise http://api.jquery.com/toggle-event/#example-0 does exactly what you wanted...

$("#div1").toggle(
  function() {
    $(this).css("background-image","url(full.png)")
  },   
  function() {
    $(this).css("background-image","url()")
  },   
  function() {
    $(this).css("background-image","url(partial.png)")
  }
});

UPDATE fn.toggle was removed from jQuery

Here are relevant posts

As long as it's a CSS-based solution (where you can just switch classes), you could do something like this (untested code):

$('#element').click(function() {
  // get current css class value.
  var class = $(this).attr('class');

  // determine/increment number.
  var nextNumber = parseInt(class.charAt(class.length - 1)) + 1;

  // if too high, reset to first one.
  if (nextNumber > 3) {
    nextNumber = 1;
  }

  // remove old class and add new class.
  $(this).removeClass(class).addClass('my_class' + nextNumber);
});

Assumption being made here that you only have one CSS class applied to the element at a time. But if that's not the case, I'm sure you can find a workaround/tweak for this.

And this is just generic enough where you can swap out your CSS class definitions without impacting the script functionality.

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