如何在点击时交换图片src? [英] How to swap image src on click?

查看:242
本文介绍了如何在点击时交换图片src?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何来回切换两个图像,如切换。



试过这个,但只适用于第一次尝试,不会切换回图像

  $(img.trigger2)。click(function(){
$(this).toggleClass(active)。next()。slideToggle(slow);
this.src = this.src.replace(collapse.gif,expand.png);
this.src = this.src.replace(expand.png,collapse.gif) ;

});


解决方案

您如何获得2张独立的图片并切换可见性,所以你不必重新加载图像?



为什么不设置src属性而不是使用.src.replace?
在jQuery中,它是这样的: -

$ $ $(img.trigger2)。click(function() {
if(this.src =='expand.png')
this.src ='collapse.gif';
else
this.src ='expand.png' ;
});


How can I swap two images back and forth, like for toggle.

Tried this but only works with the first try, does not switch the image back

$("img.trigger2").click(function(){
        $(this).toggleClass("active").next().slideToggle("slow");
        this.src = this.src.replace("collapse.gif","expand.png");
        this.src = this.src.replace("expand.png","collapse.gif");

 });

解决方案

How about you have 2 separate images and toggle visibility instead, so you don't have to keep reloading the image?

Why don't you set the src attribute instead of using a .src.replace? In jQuery, this is it:-

$("img.trigger2").click(function() {
   if (this.src == 'expand.png')
      this.src = 'collapse.gif';
   else
      this.src = 'expand.png';
});

这篇关于如何在点击时交换图片src?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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