如何使用JQ更好的实现价格倒计(降价)效果?

常见的时间倒计时在毫秒位置是快速滚动的视觉效果,我想将这种形式应用到价格倒计(降价)效果上,但是由于应用场景中还有一个降价速率的问题,我一直没法很好的实现“毫秒位置是快速滚动的视觉效果”

比如开始价格是¥257.89,降价速率为0.1元/秒,那么价格就是每秒钟降价0.1元,那么小数点第二位(9的位置)就要实现“毫秒位置快速滚动的视觉效果”

但是假如 降价速率为1元/秒,那么小数点后的数字(89的位置)都要实现“毫秒位置快速滚动的视觉效果”

我现在能做到按速率降价,但是这个“快速滚动的视觉效果”没法很好的实现

请前辈指点,非常感谢

阅读 2.5k
4 个回答

window.requestAnimationFrame是目前在JS这边能取到的颗粒度最细的时间回调,理论设计以每秒60帧的速度回调,实际上这个调用频率不是总能被保证~~~

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <style>
        .countdown{
            position: absolute;
            left:10px;
            top:10px;
            width: 100px;
            height: 50px;
        }
        .price{
            font-size: 30px;
        }
    </style>
</head>
<body>
<div class="countdown"><span class="price" data-price="123.59">123.59</span></div>
<script>

    /**
     * downRate 分/每毫秒下降金额
     * */
    function downPrice(downRate){
        var start = null;
        //金额转成分
        var originPrice=parseFloat(document.querySelector(".countdown .price").getAttribute("data-price"))*100;
        window.requestAnimationFrame(function downpriceFun(timestamp){
            var progress;
            var currentPrice;
            if(!start){
                start=timestamp;
            }
            progress = timestamp - start;
            currentPrice=Math.max(originPrice-progress*downRate,0);
            if(currentPrice){
                document.querySelector(".countdown .price").innerText=(currentPrice/100).toFixed(2);
                window.requestAnimationFrame(downpriceFun);
            }else{
                console.log(progress);
                document.querySelector(".countdown .price").innerText="0";
            }
        });
    }
    //0.1元/秒 0.1*100/1000
    //1元/秒 1*100/1000
    downPrice(1*100/1000);
</script>
</body>
</html>

建议用css来做滚动效果,js通过设置每一位滚动动画的时间来控制速率

jquery.jcountdown.js 倒计时插件吗

我本来想贴以下自己的实现,但是发现和 @kikong 的类似,就不贴了,但是到现在还是摸不准你要的是哪一种事件倒计时效果,因为我见得就有4~5种之多。

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题