我有下面的代码,一旦将对象悬停在外面,我希望数字计数回到 0%。我也想不出我们如何让这个值在加载时再次消失。你能帮我解决这个问题吗?
提前致谢。
HTML
<div class="container">
<div class="fill" data-width="80%"></div>
</div>
<div class="container">
<div class="fill" data-width="50%"></div>
</div>
CSS
.container {
position: relative;
width: 300px;
height: 30px;
background-color: blue;
margin: 10px auto;
}
.fill {
height: 100%;
width: 0;
background-color: red;
line-height: 30px;
text-align: left;
z-index: 1;
text-align: right;
}
JQuery
$(function() {
$('.container').hover( function(){
var width=$(this).find(".fill").data('width');
$(this).find(".fill").animate({ width: width }, {
duration:800,
step: function(now, fx) {
$(this).html(Math.round(now) + '%');
}
});
},
function(){
$(this).find(".fill").animate({ "width": "0px" }, 800);
});
});
jsFiddle http://jsfiddle.net/zp8pe069/
最佳答案
CSS:将 overflow: hidden
设置为 .fill
以防止文本在动画结束后可见。
HTML:从数据属性中删除 %
JS 好了。所有你需要的:
$('.container').hover(function( e ){
var $fill = $(this).find(".fill");
var width = $fill.data('width');
$fill.stop().animate({width: e.type=="mouseenter" ? width+"%" : "0%" }, {
duration : 800,
step : function(now) {
$(this).html(Math.round(now) + '%') ;
}
});
});
另请注意 .stop()
方法的使用,如果您歇斯底里地多次悬停 :) 它会阻止无尽的动画。
关于javascript - 使用 JQuery 倒数百分比,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27349790/