0

I'm looking to slide a div on and off screen, from the right hand side, on click of a link (.toggle-caption)

I had this working fine when both values were based on their position from the right, e.g.

$('.toggle-caption').toggle(
        function()
            {
            $('#caption-box').animate({right: "480px"}, 500);
            },
        function()
            {
            $('#caption-box').animate({right: "-2000px"}, 500);
            }
);

However, when attempting to toggle between a left and a right value, it stops working:

$('.toggle-caption').toggle(
        function()
            {
            $('#caption-box').animate({left: "480px"}, 500);
            },
        function()
            {
            $('#caption-box').animate({right: "-2000px"}, 500);
            }
    );

#caption-box is 2000px wide, but only a portion of this will be displayed (depends on screen resolution). However, when sliding in, it must always land 480px away from the edge of its containing div. Hence I needed a 'left' value.

Any help appreciated!

RT

4

2 回答 2

2

I ended up using the following, which works fine:

$('.toggle-caption').toggle(
    function()
        {
        $('#caption-box').animate({left: "480px"}, 500);
        },
    function()
        {
        $('#caption-box').animate({left: "100%"}, 500);
        }
);

Note that jQuery v 1.8.2 was used - Webkit browsers didn't seem to like toggling between px and percentage values in earlier versions!

于 2012-11-14T10:16:44.940 回答
0

toggle() used that way is deprecated so you should probably use a flag instead, and the data() function would make that rather easy. Also, animating to 480px from the left can be done by just subtrackting that value from the window width to get the value you would need to use it with "right" instead:

$('.toggle-caption').data('state', true).on('click', function() {
    var state = $(this).data('state'),
        dist  = state ? $(window).width() - 480 : -2000;
    $('#caption-box').stop(true, true).animate({right: dist}, 500);
    $(this).data('state', !state);
});
于 2012-11-08T18:21:06.463 回答