2014-12-08 73 views
1

我有下面的代碼,我希望數字回到0%,一旦懸停對象。另外,我無法確定如何讓這個值在加載時再次消失。你能幫我解決這個問題嗎?使用JQuery計數返回百分比

在此先感謝。

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); 
    }); 
}); 

的jsfiddlehttp://jsfiddle.net/zp8pe069/

回答

1

jsBin demo

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()的,如果你歇斯底里地徘徊多時:)它會防止無盡的動畫。

+0

非常感謝!完美的作品! :) – 2014-12-08 01:33:49

+0

@EmilGurbanov;)不客氣! – 2014-12-08 01:34:30