【问题标题】:Can't run two different animate functions无法运行两个不同的动画功能
【发布时间】:2014-02-10 10:50:26
【问题描述】:

编辑: 好,我知道了。真的很抱歉,感谢 Anthony、Rakesh 和 Nidhin :) 问题是因为我在 toTheLeft 函数中的符号“+”:

$( "#inner" ).animate({'left': '+'+ newLeft +'px'}, 'fast');

-----------------------------------^

我正在开发一个系统来连续显示视频(如播放列表),我希望用户能够点击右/左箭头来显示播放列表中的隐藏视频。很像 vimeo.com

问题是,我有两个“动画功能”,如果我在右箭头上单击超过 2 或 3 次,我将无法再单击左箭头。我的意思是,它不会为任何东西设置动画。

这是我的 JS 代码:

function toTheLeft(){
        var posLeft = $("#inner").position().left;
        var liWidth = $( ".list" ).outerWidth( true );
        var nLeft   = (liWidth+posLeft);
        if(nLeft > '0') { 
            var newLeft = '0'; 
        } else { 
            var newLeft = nLeft; 
        }
        $( "#inner" ).animate({'left': '+'+ newLeft +'px'}, 'fast' );
    }

    function toTheRight(){
        var posLeft = $("#inner").position().left;
        var liWidth = $( ".list" ).outerWidth( true );
        var inWidth = $("#inner").outerWidth( true ); // get width;
        var posRight = (inWidth + posLeft); // add the two together

        var vWidth  = $("#videos").outerWidth( true );
        var newLeft = (liWidth-posLeft);

        if(posRight > vWidth) {
            $( "#inner" ).animate({'left': '-'+ newLeft +'px'}, 'fast');
        }

    }
$("#left").on( "click", toTheLeft );

$("#right").on( "click", toTheRight );

html代码只有#right和#left两个div。一切正常,直到我点击 2 或 3 次。 div #videos 显示 5 个视频,#inner 包含 10 个视频(或更多)。

谢谢,提前。这让我发疯了。

【问题讨论】:

  • 您已经定义了 3 次“var newLeft”。没必要。只需在 if 条件之外定义“var newLeft”,然后尝试
  • newLeft 取决于 posLeft,每次单击箭头时它都会发生变化。所以我必须在每次函数运行时定义它。
  • 没关系...所以你可以全局定义 newLeft 并在不同的函数中使用不同的 newLeft 值。
  • 谢谢,这听起来很愚蠢,但我该怎么做呢? :) 抱歉,在 jquery 中还是新的。
  • 明白了!我已经编辑了我的问题。非常感谢!

标签: jquery html css function jquery-animate


【解决方案1】:

您可以尝试使用stop() 来停止正在运行的动画。

$( "#inner" ).stop().animate({'left': '+'+ newLeft +'px'}, 'fast' );

【讨论】:

  • 谢谢,但它不起作用:(。我验证了。如果我在同一个箭头上单击两次它会阻塞。但是如果我单击右箭头,然后单击左箭头它运行没有任何问题。我真的不明白。
  • 也许更多的 HTML 代码会有所帮助。你确定你没有双重身份吗?
【解决方案2】:

这是因为你的左值没有改变.. 检查这个小提琴的控制台.. 你的左值保持不变..

 var posLeft = $("#inner").position().left;
    var liWidth = $( ".list" ).outerWidth( true );
    var inWidth = $("#inner").outerWidth( true ); // get width;
    var posRight = (inWidth + posLeft); // add the two together

    var vWidth  = $("#videos").outerWidth( true );
    var newLeft = (liWidth-posLeft);

这个值没有变化

打开你的控制台检查这个 jsfiddle JSFIDDLE

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-10-25
    • 2010-11-18
    • 2020-09-12
    相关资源
    最近更新 更多