Javascript jQuery 动画和属性值的百分比
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/6877081/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
jQuery animate and property values in percentage
提问by haunted85
I trying to animate a div and I try to use some value retreived somewhere else, I know the value to be correct because I've printed out the output... so I'm wondering why doesn't it work properly?
我尝试为 div 设置动画,并尝试使用在其他地方检索到的一些值,我知道该值是正确的,因为我已经打印出输出......所以我想知道为什么它不能正常工作?
animateBar(percentage.toFixed(2)+'%');
[ . . . ]
function animateBar(percentage)
{
$('#innerBox').animate({width: percentage}, 3000);
}
回答by Alexis Canyon
It seems as though theres a bug with using a percentage with animate. http://bugs.jquery.com/ticket/10669
似乎在 animate 中使用百分比存在错误。http://bugs.jquery.com/ticket/10669
I would suggest calculating the number of pixels to add yourself, something like this may work:
我建议计算自己添加的像素数,这样的方法可能有效:
percent = 0.25;
add_width = (percent*$('#innerBox').parent().width())+'px';
$('#innerBox').animate({'width': '+='+add_width}, 3000);
回答by Caedmon
This works if you're happy using CSS3 transitions:
如果您对使用 CSS3 过渡感到满意,这会起作用:
JS:
JS:
function animateBar(percentage){
$('#innerBox').width(percentage+'%');
}
CSS:
CSS:
#innerBox{transition: 3s}
回答by Fede
This is pretty old, but this way is working for me:
这已经很老了,但这种方式对我有用:
wthSelected = 85;
$(this).animate({
width:wthSelected+'%'
}, 1500);
Also i'm using jquery-1.11.2.min.jsand jquery.mobile-1.4.5.min.js
另外我使用jquery-1.11.2.min.js和jquery.mobile-1.4.5.min.js
回答by Sebastian Perez
Try adding the units text like this:
尝试像这样添加单位文本:
function animateBar(percentage)
{
$('#innerBox').animate({width: percentage+"px"}, 3000);
}
回答by dclowd9901
It may be that you're allowing 2 decimal points to the percentage. Have you tried using an integer value instead? I'm not sure all browsers support floating percentages.
可能是您允许百分比保留 2 个小数点。您是否尝试过使用整数值?我不确定所有浏览器都支持浮动百分比。
Also, make sure $('#innerBox')
has a set width
to begin with. It doesn't have to be a percentage. It just has to be set in CSS or through a JS method.
另外,请确保$('#innerBox')
有一个width
开始。它不必是百分比。它只需要在 CSS 中或通过 JS 方法设置。
回答by Abdelkader Soudani
If it's in percentage then try this one here
如果是百分比,那么在这里试试这个
function animateBar(percentage) {
percentage = percentage+"%";
$('#innerBox').animate({'width': percentage}, 3000);
}
we're using a css property here so don't forget the single quotes, so it should be 'width' not width
我们在这里使用了一个 css 属性,所以不要忘记单引号,所以它应该是 'width' 而不是 width