使用javascript / jQuery实现多路切换的最佳方法是什么? [英] What is the best way to implement multiway toggle using javascript/jQuery?

查看:75
本文介绍了使用javascript / jQuery实现多路切换的最佳方法是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个div可以显示3个图像(在后台),每个图像表示某些变量的状态:即,部分,全部和无。对于这些状态中的每一个,我都有图像:partial.gif,full.gif和none.gif(即,这些是该div的背景图像)

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

需要:循环队列喜欢切换效果以此顺序更改图像partial - > full - > none - > partial

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

因此,如果当前图像为'partial.gif'且用户点击div,背景图像变为序列中的下一个,即full.gif(如果它当前是full.gif,它将变为none.gif,而变为partial.gif,依此类推)。

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 i.e., full.gif (and if it is currently full.gif it changes to none.gif and that to partial.gif and so on).

天真的解决方案:有一堆if / else或switch-case并检查当前的(图像),然后根据数组查找决定下一个。这是最好的方式吗?我可以以某种方式利用jQuery的切换功能吗?

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:它不仅限于图像,但也可以用于不同的背景颜色序列等,我喜欢知道这是一个很好的通用方式,即,该示例可能是特定于背景图像,但如果我改变了部分代码的背景颜色或字体它应该仍然有效。我不希望它是纯粹的通用,但只是足够,所以很容易修改其他属性。如果没有,那也没关系。只是一个想法:)

(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 i.e., 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/

确切地说, http: //api.jquery.com/toggle-event/#example-0
完全符合您的要求...

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已从jQuery中移除

UPDATE fn.toggle was removed from jQuery

以下是相关帖子

  • Where has fn.toggle( handler(eventObject), handler(eventObject)...) gone?
  • Toggle stopped working after jquery update

这篇关于使用javascript / jQuery实现多路切换的最佳方法是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆