使用jQuery切换图像src

我编写了一些代码来切换图像的src,并暂停/恢复jQuery cycle2插件。

我不确定为什么它不起作用,并希望得到一些帮助。

$('.play-pause').click(function(){ if ($(this).attr('src', '/images/template/pause.png')) { $(this).attr('src', '/images/template/play.png'); $('.cycle-slideshow').cycle('pause'); } else if ($(this).attr('src', '/images/template/play.png')) { $(this).attr('src', '/images/template/pause.png'); $('.cycle-slideshow').cycle('resume'); } }); 

如果我删除’else if’语句,则第一个’if’语句有效。

谢谢您的帮助。

杰夫

对于UI元素,例如暂停/播放按钮,您应该使用CSS背景 ,而不是内嵌图像。 那就是你可以简单地交换类名来改变图像。

您可以使用内嵌图像,但应再次简化使用类名。

 $('.play-pause').click(function(){ if (!$(this).hasClass('play')) { $(this).attr('src', '/images/template/play.png'); $(this).addClass('play') $('.cycle-slideshow').cycle('pause'); } else { $(this).attr('src', '/images/template/pause.png'); $(this).removeClass('play') $('.cycle-slideshow').cycle('resume'); } }); 

更通用,只检查图像的来源,而不是整个字符串:

 $('.play-pause').on('click', function(){ var isPause = this.src.indexOf('pause.png') != -1; this.src = isPause ? this.src.replace('pause.png', 'play.png') : this.src.replace('play.png','pause.png'); $('.cycle-slideshow').cycle(isPause ? 'resume' : 'pause'); }); 
 $(document).ready(function(){ $(".bulb").click(function(){ var src = $(this).attr('src'); var newsrc = (src=='images/dim.png') ? 'images/glow.png' : 'images/dim.png'; $(this).attr('src', newsrc ); }); }); 

甚至可以减少线路,但避免混淆。 基本上,它获取当前状态属性源并检查和分配所需的源。

我知道这是一个迟到的答案但是如何使用简单的东西:

 $('.play-pause').click(function () { var _this = $(this); if (_this.attr("src") == '/images/template/pause.png') { _this.attr('src', '/images/template/play.png'); $('.cycle-slideshow').cycle('pause'); } else { _this.attr('src', '/images/template/pause.png'); $('.cycle-slideshow').cycle('resume'); } }); 

有时候想要直接交换图像src而不是在CSS中处理它(实际上是处理奇怪的错误)实际上是合理的。 我在这种情况下所做的是编写一个简单的辅助函数,它可以在初始src和备用src之间切换,您也可以在image元素本身上指定,如下所示:

 function toggleImgSrc(jQueryObj) { tmp = jQueryObj.attr('src'); jQueryObj.attr('src', jQueryObj.attr('toggle_src')); jQueryObj.attr('toggle_src', tmp); } 

而image元素本身只有一个名为’toggle_src’的额外属性(或者你可以根据需要动态添加它):

  

这是另一种方法:

   

而对于jQuery

 /* jQuery */ $('#magic-toggle').click(function() { if($('.fun-img').attr('src') === plus) { $('.fun-img').attr('src', minus); } else { $('.fun-img').attr('src', plus) } }) 

可能需要一些有趣的动画,但可以完成工作。

这是一个片段:

 var plus = 'https://d30y9cdsu7xlg0.cloudfront.net/png/5805-200.png'; var minus = 'https://d30y9cdsu7xlg0.cloudfront.net/png/5802-200.png'; $('#magic-toggle').click(function() { if ($('.fun-img').attr('src') === plus) { $('.fun-img').attr('src', minus); } else { $('.fun-img').attr('src', plus) } }) 
 .fun-img { width: 80px; }