【问题标题】:a div animates outside the screen with rapid clicking快速点击屏幕外的 div 动画
【发布时间】:2013-01-04 07:53:18
【问题描述】:

我有这个代码:

$(document).ready(function(){

    $(".subscriptions").click(function (){

        if($(".pollSlider").css("margin-right") == "-200px"){
            $('.pollSlider').animate({"margin-right": '+=200'});
            }else{
            $('.pollSlider').animate({"margin-right": '-=200'});
            }
        });

//other exceptions

if($(".pollSlider").css("margin-right") > "200px"){
    $(".pollSlider").css({'margin-righ':'200px'});
    }
if($(".pollSlider").css("margin-right") < "0px"){
    $(".pollSlider").css({'margin-righ':'0px'});
    }
 }); 

这是css:

.pollSlider{
    overflow: auto;
    top:0px;
    position:fixed;
    height:100%;
    background:red;
    width:200px;
    right:0px;
    margin-right: -200px;
    z-index:100;
}

我有一个 div,当用户单击一个按钮时,div 从左侧 200px 滑入屏幕,当用户再次单击同一个按钮时,div 动画向右 200px。这个系统工作得很好,但问题是,如果用户在 div 向左或向右动画时继续单击,则 div 将在屏幕之外(向右)动画,并且当用户再次单击时不会再次返回。所以我尝试添加 //other 异常,但那些 if 语句不起作用。我该如何解决这个问题?

【问题讨论】:

  • 你试过在.animate()之前使用.stop()吗?
  • 这样 $('.pollSlider').stop(); ??
  • 是的,它应该类似于$('.pollSlider').stop().animate()

标签: javascript jquery html css jquery-ui


【解决方案1】:

我创建了一个 Demo,我试图在其中实现您想要产生的效果。在 cmets 中提到,jQuery .stop(…) 用于在开始下一个动画之前清空动画队列。

我还将单位从相对(+=200-=200)更改为固定数字(0-width)。如果您假设动画将在中途停止并且您需要重新制作动画,则您需要使用固定数字,或者在每个新动画之前即时进行计算。

【讨论】:

    【解决方案2】:

    我对这类问题的解决方案是添加一个全局变量,在用户单击后将其设置为 false,并在动画完成后将其设置回 tru:

    var allowAnimate = true;
    $(document).ready(function(){
    
    $(".subscriptions").click(function (){
        if(allowAnimate){
        if($(".pollSlider").css("margin-right") <= "-200px"){
            allowAnimate = false;
            $('.pollSlider').animate({"margin-right": '+=200'}, function(){allowAnimate = true});
            }else if($(".pollSlider").css("margin-right") >= "200px")){
            $('.pollSlider').animate({"margin-right": '-=200'}, function(){allowAnimate = true});
            }
        }
        });
    
    //other exceptions
    ....
    

    因此,如果用户单击按钮,则检查变量 allowAnimate 是否为 true,我将其设置为 false,然后动画将开始,在动画回调函数中我将其设置回 true

    【讨论】:

    • 我刚刚尝试了你的代码,但我仍然遇到同样的问题。
    • 是的,因为您没有保护代码 :) 。您还应该检查什么:if($(".pollSlider").css("margin-right") &gt;= "200px")
    猜你喜欢
    • 2015-11-23
    • 1970-01-01
    • 2017-03-15
    • 1970-01-01
    • 2011-03-02
    • 2023-03-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多