开发者

toggle two images by fading

H开发者_高级运维ow can I toggle two images by fading using jQuery .fadeToggle method.


You must put the 2 elements you want to crossfade one on top of the other by using position:absolute;. You begin by hiding one. To make a crossfade, you just run simultaneously a fadeToggle() on each of the 2 elements.

The HTML:

<div id="d1" style="background-color:red;"></div>
<div id="d2" style="background-color:blue;"></div>
<span>Click</span>

The CSS:

#d1, #d2 {position:absolute;
    top:12px;
    left:12px;
    width:120px;
    height:120px;}

span {position:absolute;
    top:200px;
    left:12px;
    cursor:pointer;}

The Javascript:

$(document).ready(function(){
  $("#d1").show();
  $("#d2").hide();
  $("span").click(function(){ // For demo's sake we attach the crossFade to a click event.
    $("#d1").fadeToggle(500);
    $("#d2").fadeToggle(500);
  });
});


Is this what you're trying to do? http://jsfiddle.net/U5GSy/

Here's the code in the fiddle

$(function(){
    $("input:button").click(function(){
        $(".cat").fadeToggle("fast");
    });
});

<img id="cat1" class="cat" src="http://www.crystalinks.com/catop.jpg" alt="" />
<img id="cat2" class="cat" src="http://blindgossip.com/wp-content/uploads/2010/11/cat-claw-1.jpg" alt="" />
<br />
<input type="button" value="Go Kitty Go" />

#cat1 {
    position:absolute;
    top:0;
    left:0;
}

#cat2 {
    display:none;
    position:absolute;
    top:0;
    left:0;
}
input {
    position:absolute;
    top: 220px;
}


Use fadeToggle twice. This will toggle between 3 images. just set imgno to change it. And also remember that this should be greater than the sources in src array.

<script src="jquery.js"></script>
<body>
<div id="hold"><img src="img1" />Hold</div>
<script>

var src= ['src1', 'src2', 'src3'];
var count=0;
var imgno=3;

$("#hold").click(
    function (){
        $(this).fadeToggle("fast", 
            function (){
                $(this).find('img').attr('src', src[++count%imgno]);
                $(this).fadeToggle("fast", function (){ return true; });
            }
            )
    }  
  )   
</script>
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜