jQuery的。用动画改变div宽度不起作用

时间:2012-05-18 21:40:42

标签: jquery html css jquery-animate

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

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

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

但是用css工作改变宽度:

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

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

4 个答案:

答案 0 :(得分:2)

也许您需要引用widthPercent

这对我有用

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

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

问题应该在你的widthPercent定义中。

答案 1 :(得分:1)

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操作

答案 2 :(得分:0)

这就是你的意思:

jQuery的:

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

CSS:

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

JSFiddle

答案 3 :(得分:0)

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

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

这是jsfiddle说明的内容。

相关问题