I want to be able to change the src of an image back and forth between two different images. I have attempted various toggle and fadeToggle efforts but toggle disturbs the flow of the page. I have it working to a certain extent but it only works for two clicks. One to change then one back again. Can anyone offer any suggestions for a way to be able get the toggle effect without the 'display : none' factor upsetting the flow. I've tried various things from Stack without success. Thanks in advance, folks - T
$('#myButton').click(function(){
$('.myImg').fadeOut('slow', function() {
$(this).attr('src', 'img/after.png').fadeIn('slow', function() {
$('#myButton').click(function() {
$('.myImg').fadeOut('slow', function() {
$(this).attr('src', 'img/before.png');
});
});
});
});
});
答案 0 :(得分:0)
您可以尝试使用if else
$('#myButton').click(function(){
var myimg = $('.myImg'),
src = (myimg.attr('src') == 'img/after.png') ? 'img/before.png' : 'img/after.png' ;
myimg.stop().fadeOut('slow', function(){
myimg.attr('src', src).fadeIn('slow');
});
});
答案 1 :(得分:0)
这可能是一个解决方案:
$('#myButton').click(function(){
if($myImg.attr("src")==src1){
$myImg.fadeOut("slow", function() {
$(this).attr("src", src2).fadeIn("slow");
});
} else {
$myImg.fadeOut("slow", function() {
$(this).attr("src", src1).fadeIn("slow");
});
}
});
不确定这是您要找的内容:jsfiddle