jQuery- dynamically alternate between image sources within an animated div

非 Y 不嫁゛ 提交于 2019-12-24 00:11:59

问题


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" 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');
    });
});

回答1:


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.




回答2:


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!




回答3:


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

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


来源:https://stackoverflow.com/questions/5060693/jquery-dynamically-alternate-between-image-sources-within-an-animated-div

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!