【问题标题】:jquery. changing div width with animation does not worksjQuery。用动画改变 div 宽度不起作用
【发布时间】:2012-05-18 21:40:41
【问题描述】:

大家好,我有变量(widthPercent),我存储百分比,例如:67.33%

当我尝试使用 jquery 动画更改宽度时,它不起作用:

$(this).animate({
        width: widthPercent,
    }, 2500);
});

但是用 css 改变宽度效果很好:

$(this).css('width', widthPercent);

有人知道我的问题是什么吗?

【问题讨论】:

  • 你能告诉我们你的 widthPercent 定义吗?

标签: jquery html css jquery-animate


【解决方案1】:

也许你需要引用宽度百分比

这对我有用

$(document).ready(
                function(){
                    var widthPercent = "35%";
                    $("#btn").click(
                    function(){

                        $(this).animate({
                            width: widthPercent,
                        }, 2500);
                    });
                }
            );

问题应该出在您的 widthPercent 定义中。

【讨论】:

  • 也许你错过了 %?或声明 int (不带引号)尝试通过将您的 widthPercent 编辑为末尾带有 % 的字符串
  • 这里有一个多余的逗号
  • @Brandt Solovij 没关系
  • 哈哈,你是对的 - 我过去曾遇到过问题 - 去看看。
【解决方案2】:

http://api.jquery.com/animate/

var widthPercent = "35%";

$(this).animate({
        width: "'"+widthPercent+"'"   // YOU ALSO HAD AN EXTRA COMMA HERE MEANING IT WAS EXPECTING ANOTHER ARGUMENT -- extra quotes may or may not be necessary depending on what your actual variable looks like
    }, 2500);
});

http://jsfiddle.net/A2bdQ/5/

在使用 % 符号时也一定要使用引号,否则可能会被视为内联 mod 操作

【讨论】:

  • 那么还有其他问题。哈 - 额外的逗号。更多的咖啡时间。
【解决方案3】:

您需要在宽度值中添加一个 '%' 字符,如下所示:

$(this).css('width', widthPercent + '%')

这是一个jsfiddle 说明它。

【讨论】:

    【解决方案4】:

    这是你的意思吗:

    jQuery:

    $('#foo').click(function(){
        var widthPercent = '66%';
        $(this).animate({
            'width': widthPercent,
        }, 2500);
    });
    

    CSS:

    #foo{
       width:300px;
       background:#ff0000;
       height:100px;   
    }
    

    JSFiddle.

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2023-04-09
      • 2014-02-28
      • 1970-01-01
      • 2014-11-01
      • 1970-01-01
      • 2014-07-17
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多