2013-07-04 99 views
1

我有兩種價格在HTML中列出。一個是總計價格和其他價格是折扣價(折扣價格總計與折扣適用於它):Jquery:使用計數器顯示折扣

<ul> 
<li class="discounted-price">180.99</li> 
<li class="special">Grand Total: £<b id="price">186.95</b></li> 
</ul> 

<a class="trigger" href="#">Link</a> 

當用戶點擊鏈接,我想大的數字總價格「向下滾動」(例如像收銀機一樣)到折扣價格的價值。

我發現這example如何使用Jquery實現它。然而,在這個例子中,他們的例子不是價格,所以許多數字都以逗號分隔。

我試圖STIP了所有不必要的代碼,但現在我的價格是這樣的: £180.99008006406564

如何限制我的價格只是小數點後兩位。我知道Javascript有一個用於控制小數位的tofixed()工具,但似乎無法在不破壞動畫的情況下讓它在我的代碼中工作。

這裏是我的代碼:

$(document).ready(function() { 

    // Animate the element's value from x to y: 
    $('.trigger').live('click', function() { 
     var originalprice = $('#price').text(); 
     var discount = $('.discounted-price').text(); 

     $({ 
      someValue: originalprice 
     }).animate({ 
      someValue: discount 
     }, { 
      duration: 3000, 
      easing: 'swing', 
      // can be anything 
      step: function() { 
       $('#price').text(this.someValue); 
      } 
     }); 

    }); 
}); 

HERE IS JSFIDDLE

回答

1

使用這種方法在step回調:

$('#price').text(parseFloat(this.someValue).toFixed(2)); 

jsFiddle

2

我做點事荷蘭國際集團這樣的:

jQuery(function($) { 
    $(document).on('click', '.trigger', function() { 
     var originalprice = parseFloat($('#price').text()), 
      discount  = parseFloat($('.discounted-price').text()); 

     $({someValue: originalprice}) 
      .animate({ 
       someValue: discount 
      }, { 
       duration: 3000, 
       easing: 'swing', 
       step: function (now) { 
        $('#price').text(parseInt((now * 100),10)/100); 
       } 
     }); 
    }); 
}); 

FIDDLE