jQuery 切换以更改图像
我有一个包含图像的 div 列表:
<div class="wizard-img"><%= image_tag("sources/pix/nyt.png") %></div>
<div class="wizard-img"><%= image_tag("sources/pix/theguardian.png") %></div>
当用户单击该 div 时,我希望它将图像更改为 x-on.png,再次单击时,它将更改为 x-off.png,并且第三次单击时,它应该恢复为 x.png。
是否可以在不为每个图像更改手动指定 jQuery 的情况下执行此操作? 我可以遍历 div 并找到图像名称,然后简单地将 -off/-on 附加到图像吗?
谢谢!
I have a list of divs with images in them:
<div class="wizard-img"><%= image_tag("sources/pix/nyt.png") %></div>
<div class="wizard-img"><%= image_tag("sources/pix/theguardian.png") %></div>
When a user clicks the div, I'd like it to change the image to x-on.png, when clicked again, it'll change to x-off.png, and when clicked a third time it should revert to x.png.
Is it possible to do this without manually specifying jQuery for every image change? Can I traverse the div and find the image name, and simply append the -off/-on to the image?
Thanks!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(8)
也许 CSS sprites 适合您?
这将使您不必每次单击图像(按钮?)时加载单独的图像,并且您可以通过添加和删除 css 类来解决您的问题,例如:
Perhaps CSS sprites would work for you?
That would save you from loading a separate image every time you click the image (button?), and you could solve your problem by adding and removing a css-class, e.g.:
http://docs.jquery.com/Events/toggle
http://docs.jquery.com/Events/toggle
CSS Sprites 确实是实现此目的的方法,但为了完整起见,这里还有另一个选择。
通常我是最后一个接触正则表达式的人,但我认为他们会在这里提供帮助
CSS Sprites would indeed be the way to do this, but just for completeness, here's another option.
Normally I'm the last to reach for a regexp, but I think they'll help here
FWIW,我建议您使用纯 CSS 和背景图像来执行此操作。 在我看来,这并不是真正的普通图像,而是“按钮”。
FWIW, I suggest you do this using plain CSS and
background-image
. It sounds to me that this is not really normal images, but rather "buttons".我发现这个插件对于执行类似于您所要求的操作很有用:
http://www.malsup.com /jquery/循环/
I have found this plugin useful to do something similar to what you asked:
http://www.malsup.com/jquery/cycle/
http://kaidez.com/tutorial-simple- effective-jquery-image-翻转/
http://kaidez.com/tutorial-simple-effective-jquery-image-rollover/
我创建了插件 swapimg: http://xuannd.wordpress.com /2010/12/03/jquery-swap-images-easy/
使用:$('.swapimg').swapimg();
选择:$('.swapimg').swapimg({imgOn:"_on.png", imgOff:".png"});
I created plugin swapimg: http://xuannd.wordpress.com/2010/12/03/jquery-swap-images-easy/
use: $('.swapimg').swapimg();
opt: $('.swapimg').swapimg({imgOn:"_on.png", imgOff:".png"});