使用 jquery 中的百分比动画 div 的宽度

Animating the width of a div using percentages in jquery

我正在尝试在单击按钮(在本例中为另一个 div)时以百分比更改 div 的宽度。我让它在 example, but cannot successfully recreate it in the actual code for my site, an example of which is here 中工作。它们和我的眼睛一模一样,但显然有问题。

正在使用的javascript是:

$('#button').click(function() {
if(!collapsed){
    $('.left').animate({width: '10%'});
} else {
    $('.left').animate({width: '50%'});
}
collapsed = !collapsed; });

然而,至少在第二个例子中,没有任何结果。

您的版本有两个问题:

  1. jsFiddle 不包含 jQuery。
  2. 您没有定义 collapsed 变量,因此您在控制台中遇到错误。

解决了这些问题,它就起作用了。另请注意,您可以使用三元表达式将宽度更改为一行:

var collapsed = false;
$('#button').click(function() {
    $('.left').animate({ width: collapsed ? '50%' : '10%' });
    collapsed = !collapsed;
});

Working example

可能还值得在调用 animate() 之前添加 stop(true) 以防止连续点击填满动画队列。