我从 div click 和 a 获得方向,试图将其传递给 animate 函数
var direction = $(this).attr('class').split(' ')[1];
var scrollAmount = 285;
$('#slider').animate({direction:'-=' + scrollAmount}, 'slow');
怎么了?
谢谢
我从 div click 和 a 获得方向,试图将其传递给 animate 函数
var direction = $(this).attr('class').split(' ')[1];
var scrollAmount = 285;
$('#slider').animate({direction:'-=' + scrollAmount}, 'slow');
怎么了?
谢谢
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');
没有这样的属性animate
称为方向,因此错误。检查文档。
根据评论编辑
然后你应该在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">«</button> <button id="right">»</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>