开发者

jQuery- dynamically alternate between image sources within an animated div

I have a menu that is animated to slide across the page when triggered by clicking on an image of an arrow. I'd like to switch the arrow to a different image source once the menu's animation has completed, and then return back to the original file when the menu has been closed.

Best way to do this? Thank you!

HTML:

<div id="slider">
     <div id="trigger_right">
          <img class="arrow_small" 开发者_JS百科src="images/left_small.png" alt="slide menu out" />
     </div>
     <div class="trans" id="overlay"></div>
     <div id="content">
          <p>This is content</p>
     </div>
</div>

Javascript:

$(function() {
    $('#trigger_right').toggle(function (){
        $('#slider').animate({'width':'100%'}, 1500);
            $('.arrow_small').attr('src','images/right_small.png');
    }, function() {
        $('#slider').animate({'width':'30px'}, 1500);
            $('.arrow_small').attr('src','images/left_small.png');
    });
});


jQuery's .animate has a callback that is called when the animate is finished so you can use that to change the images at the appropriate time:

$(function() {
    $('#trigger_right').toggle(function () {
        $('#slider').animate({'width':'100%'}, 1500, function() {
            $('.arrow_small').attr('src','images/right_small.png');
        });
    }, function() {
        $('#slider').animate({'width':'30px'}, 1500, function() {
            $('.arrow_small').attr('src','images/left_small.png');
        });
    });
});

The above assumes that you only have one .arrow_small element of course. Using a class for the arrow and a sprite sheet for the images would be better but that would only require changing the $('.arrow_small').attr() parts to $('.arrow_small').toggleClass() calls as Rob suggests.


If I understand correctly, you only want the images to change after the menu animation has completed.

One way, perhaps not the best, would be to make the JavaScript that changes the src attribute occur after a set period of time using setTimeout(). Instead of:

$('.arrow_small').attr('src','images/right_small.png');

You would have:

setTimeout("toggleImages()", 1500);

function toggleImages(){
    // some code to toggle them
}

I haven't tested this, but give it a try. Hope it helps!


I would suggest you set the images up in CSS as classes and then do something like:

.toggleClass("right-small left-small");
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜