Unable to move div back to original position after slide

时间:2015-09-29 00:46:17

标签: jquery slide

I have a problem with a slidetoggle. The black box after clicking slides the second div back in which is great but itself will not slide back to it's original position. How can I fix this?

I am using Jquery UI at the moment.

Here is the code:

#recommended-product-block{
    position: absolute;
    top:225px;
    right:0;
    z-index: 999999;
    width:100px;
}
#weather{
    width:150px;
    position:absolute;
    right: 0;
}

<div id="recommended-product-block">
    <h1>Div box to initiate slide toggle</h1>
</div>

<div id="weather">
    <h1>Box that slides in and out</h1>
</div>

$(document).ready(function() {

    $('#weather').hide();

    $(function () {
        $("#recommended-product-block").click(function () {
            $(this).animate({ right: '+150' }, 400 );
            $( "#weather" ).toggle( "slide" );
        });
    });

});

1 个答案:

答案 0 :(得分:1)

如果你要在两个<div>标签之间切换,那么这很简单。第一个div将被隐藏。点击第二个div,第一个div将滑动,第二个div将消失。点击第一个div第二个div将滑动,第一个div将消失。

$('#weather').hide();

$(function () {
    $("#recommended-product-block").click(function () {            
        toggle();
    });

    $("#weather").click(function () {            
        toggle();
    });
});

function toggle(){
    $( "#weather" ).toggle('slide');
    $( "#recommended-product-block" ).toggle('slide');
}

Fiddle

(为清晰起见添加了边框)

修改

要控制速度,请使用此切换功能

function toggle(){
    $('#weather').toggle('slide', {direction:'left'}, 300);
    $( "#recommended-product-block" ).toggle('slide', {direction:'left'}, 300);
}

修改(根据评论)

$('#weather').hide();

$(function () {
    var notClicked = true;

    $("#recommended-product-block").click(function () { 

        $( "#weather" ).toggle('slide', 400);

         if(notClicked) {
            $(this).animate({'right':150}, 400);  
          }
          else
          {
             $(this).animate({'right':0},400);
          }

          notClicked = !notClicked;        
    });

 });

Updated Fiddle