如何使用函数.toggle?

时间:2013-05-20 01:19:42

标签: jquery function jquery-animate

如何使用.animate制作倒车动画? 我在其他地方读到了函数.toggle,但是当我使用它时,这个函数会在没有“点击”的情况下自动启动。我希望它(函数)仅在我(或用户)单击它时开始。

$(document).ready(function(){
    $("#dae").toggle(
        function(){
            $("#dae").click(function(){
                $("#dae").animate({left:'50px', top:'100px'}, "slow");
                $("#dae").animate({opacity:0.1}, "slow");
                $("#dae").animate({opacity:1.0}, "slow");
            });
        }, function(){
            $("#dae").click(function(){
                $("#dae").animate({opacity:1.0}, "slow");
                $("#dae").animate({opacity:0.1}, "slow");
                $("#dae").animate({left:'10px', top:'20px'}, "slow");
            });
        }
    )
});

问题是:当浏览器启动时,div消失。

2 个答案:

答案 0 :(得分:4)

切换时不需要“点击”事件。 .toggle()基于click事件。

所以这样设置:

$("#dae").toggle(
    function(){

            $(this).animate({left:'50px', top:'100px'}, "slow");
            $(this).animate({opacity:0.1}, "slow");
            $(this).animate({opacity:1.0}, "slow");

    }, function(){

            $(this).animate({opacity:1.0}, "slow");
            $(this).animate({opacity:0.1}, "slow");
            $(this).animate({left:'10px', top:'20px'}, "slow");

    }
)

尝试以上操作,看看它对您有何帮助。如果你有任何问题,请告诉我。

编辑:注意如下所示,这不适用于较新的版本。 jquery因为它不再支持这两个函数。好的和有效的一点。

答案 1 :(得分:2)

试试这个: -

我不确定您使用的是哪个jquery版本,但.toggle()不再需要2个回调。你也需要点击而不是执行切换,这就是为什么你看到它最初被执行的原因。

Demo

$("#dae").click(function(){
    var $this = $(this);
    if ($this.is('.animate')) //Just add this class to detect the state.
    {

            $this.animate({left:'50px', top:'100px'}, "slow")
             .animate({opacity:0.1}, "slow")
             .animate({opacity:1.0}, "slow");
     }
    else
    {
         $this.animate({opacity:1.0}, "slow")
         .animate({opacity:0.1}, "slow")
         .animate({left:'10px', top:'20px'}, "slow");
    }
   $this.toggleClass('animate'); //add/remove class based on its previous state.
});