2013-07-04 42 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