开发者

jQuery animate a div while subsequently fading triggers in and out

I've got a menu bar that slides across the page when an image is clicked, and slides back when an alternate image is clicked. I'd like to included fading the just-clicked image out and fading the unclicked image in as the menu bar is animated. I'm sure this can be done with a dynamic function.. but it's beyond my understanding.

Thank you for your help!

HTML:

<div id="main">
    <div id="trigger_left">
        <img class="arrow_small" src="images/left_small.png" alt="slide menu out" />
    </div>
    <div id="trigger_right">
        <img class="arrow_small" src="images/right_small.png" alt="slide menu in" />
    </div>
    <div id="slider">
         <p>This is Content</p>
    </div>
</div>

Javascript:

$(document).ready(function() {
    //Page Load
    $('#slider').css({
        width: '30px'
    });
    // Navigation drop down menu
    $('#trigger_left').click(function() {
        $('#slider').animate({
            width: '100%'
        }, 1500);
    });
    $('#trigger_right').click(function() {
        $('#slider').animate({
            width: '30px',
        }, 1500);开发者_C百科
        }

    );
});


First of all you might want to cache your jQuery objects to improve the performance and readability, then you might want to add the .stop() method to halt current animation and fire new one from current point rather then seeing animations queueing and looping and acting weird. then add the .fadeOut() and .fadeIn() on the triggers when click occurs. Ah and you should get used to using .bind() rather then .click(), .keydown() etc. as these are aliases to bind method so it's more efficient to use bind directly. Apart of that it's easier to use events namespaces with bind and more. Check the jQuery API!

var trigger_left = $('#trigger_left'),
    trigger_right = $('#trigger_right'),
    slider = $('#slider');

slider[0].style.width = "30px"; // and use native js where you can 
        //- it speeds things up and prepares you for when you can't use jQ :)

trigger_left.bind('click', function() {
    trigger_left.stop().fadeOut();
    trigger_right.stop().fadeIn();
    slider.stop().animate({
        width: '100%'
    }, 1500);
});
trigger_right.bind('click', function() {
    trigger_right.stop().fadeOut();
    trigger_left.stop().fadeIn();
    slider.stop().animate({
        width: '30px',
    }, 1500);
    }

);
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜