【问题标题】:jquery passing in direction to animate()jquery 方向传递给 animate()
【发布时间】:2012-05-05 22:52:06
【问题描述】:

我从 div click 和 a 获取方向,试图将其传递给 animate 函数

var direction = $(this).attr('class').split(' ')[1];
var scrollAmount = 285;
$('#slider').animate({direction:'-=' + scrollAmount}, 'slow');

怎么了?

谢谢

【问题讨论】:

    标签: jquery function jquery-animate direction


    【解决方案1】:

    animate 函数的第一个参数接受 CSS 属性,说明动画结束的最终属性。你不能那样传递方向。听起来您要么想设置 left 或 scrollLeft 量并改变方向,那么您应该查看方向的值,并根据您想要的方式使用 -= 或 +=。

    var sign;
    
    if (direction == 'left') sign = '-=';
    else sign = '+=';
    
    $('#slider').animate({left:sign + scrollAmount}, 'slow');
    

    或者如果它是你试图传递的属性

    var prop = {};
    prop[direction] = scrollAmount;
    $('#slider').animate(prop, 'slow');
    

    【讨论】:

    • 如果我不想使用 '-=' 或 '+=' 运算符,因为 chrome 中的缩放问题?是否有“等效”调用???
    【解决方案2】:

    animate 中没有这样的属性称为方向,因此出现错误。检查documentation

    根据评论编辑

    那么你应该在css中将left或right作为第一个参数传递给动画

    jQuery animate API 文档中的示例代码

    <!DOCTYPE html>
    <html>
    <head>
      <style>
    div {
      position:absolute;
      background-color:#abc;
      left:50px;
      width:90px;
      height:90px;
      margin:5px;
    }
    </style>
      <script src="http://code.jquery.com/jquery-latest.js"></script>
    </head>
    <body>
      <button id="left">&laquo;</button> <button id="right">&raquo;</button>
    <div class="block"></div>
    
    <script>
    $("#right").click(function(){
      $(".block").animate({"left": "+=50px"}, "slow");
    });
    
    $("#left").click(function(){
      $(".block").animate({"left": "-=50px"}, "slow");
    });
    
    </script>
    
    </body>
    </html>
    

    【讨论】:

    • 我试图通过“左”或“右”的方向
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-06-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多