数字滚动插件(css3 只兼容高版本浏览器,供学习)

原创
2018/04/27 13:17
阅读数 519

之前一直有人在问我, 数字滚动插件怎么做的。今天在这里给大家写个demo,支持小数的数字滚动插件,见下面的代码。

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <script src="https://cdn.bootcss.com/jquery/2.2.4/jquery.min.js"></script>
    <script src="https://cdn.bootcss.com/mathjs/4.1.2/math.min.js"></script>
    <title>无缝数字滚动</title>
    <style>
        body {
            margin: 40px;
            padding: 0;
        }

        .number-run {
            position: relative;
            display: inline-block;
        }

        .number-run:after {
            content: "";
            display: block;
            height: 0;
            clear: both;
            visibility: hidden;
        }

        .number-run-item {
            position: relative;
            vertical-align: top;
            text-align: center;
            overflow: hidden;
            float: left;
        }

        .number-run-box {
            position: relative;
            transform: translateY(0);
        }

        .number-run-item-inner {
            display: block;
        }
    </style>
</head>

<body>
    <br/>
    <br/>
    <div id="box"></div>
    <br/>
    <br/>
    <div id="box2"></div>
    <br/>
    <br/>
    <div id="box3"></div>
</body>
<script>
    (function ($) {
        $.fn.numberRun = function (setting) {
            const defaults = {
                style: { // 数字盒子的样式
                    width: '14px', // 文字间隔
                    height: '14px' // 文字高度 
                },
                speed: '0.5s', // 动画时间
                num: 1234567 // 初始化值,请传入字符串
            };
            setting = $.extend({}, defaults, setting);

            // 设置dom
            const setHTML = (set, num) => {
                let numArr = (num + '').split('');
                let shtml = `<div data-num="${num}" class="number-run" style="height: ${set.style.height};">`;
                let styl = [];
                set.style['line-height'] = set.style.height;
                for (let key in set.style) {
                    styl.push(`${key}: ${set.style[key]}`);
                }
                numArr.forEach(elem => {
                    if (elem === '.') {
                        shtml += `<div style="${styl.join(';')}" class="number-run-item number-run-dot">${elem}</div>`;
                    } else {
                        shtml += `
                        <div data-num="${elem}" style="${styl.join(';')}" class="number-run-item number-run-num">
                            <div style="transition: ${set.speed}; 
                            transform: translateY(0); 
                            -webkit-transform: translateY(0); 
                            height: ${parseInt(set.style.height, 10) * 10}px;" class="number-run-box">
                                ${'0123456789'.split('').map((num, index) => {
                                return `<span style="${styl.join(';')};" class="number-run-item-inner">${num}</span>`;
                            }).join('')}    
                            </div>
                        </div>`;
                    }
                });
                shtml += '</div>';
                return shtml;
            }

            // 执行动画
            const doAnimate = () => {
                $(this).hide(0).show(0);
                $(this).find('.number-run-num').each(function () {
                    let num = parseInt($(this).attr('data-num'), 10);
                    $(this).find(".number-run-box").css({
                        '-webkit-transform': `translateY(-${num * parseInt(setting.style.height, 10)}px)`,
                        'transform': `translateY(-${num * parseInt(setting.style.height, 10)}px)`
                    });
                });
            }

            // 判断数字是否长度一致
            const checkNum = (num1, num2) => {
                if (num1.length === num2.length) {
                    let n1 = num1.split('.');
                    let n2 = num2.split('.');
                    if (n1[0].length === n2[0].length && n1[1] === undefined && n2[1] === undefined) {
                        return true;
                    } else if (n1[0].length === n2[0].length && n1[1].length === n2[1].length) {
                        return true;
                    } else {
                        return false;
                    }
                } else {
                    return false;
                }
            }

            // 执行run
            const run = (num) => {
                const $run = $(this).find('.number-run');
                let prevNum = $run.attr('data-num');
                $run.attr('data-num', num);
                if (checkNum(num + '', prevNum)) {
                    let numArr = (num + '').split('');
                    $(this).find('.number-run-item').each(function (index) {
                        if (numArr[index] !== '.') {
                            $(this).attr('data-num', numArr[index]);
                        }
                    });
                } else {
                    $(this).html(setHTML(setting, num));
                }
                doAnimate();
            };

            // 初始化数字
            $(this).html(setHTML(setting, setting.num));
            // debugger
            doAnimate();

            return { run, checkNum };
        }
    })(jQuery);

    $(function () {
        const test = $('#box').numberRun({
            speed: '2s',
            num: 1224.15,
            style: {
                'height': '30px',
                'width': '20px',
                'font-size': '30px'
            }
        });

        const test2 = $('#box2').numberRun({
            speed: '0.3s',
            num: 12223.13,
            style: {
                'height': '16px',
                'width': '12px',
                'font-size': '14px'
            }
        });

        const test3 = $('#box3').numberRun({
            speed: '0.3s',
            num: 342.551,
            style: {
                'height': '16px',
                'width': '14px',
                'font-size': '16px',
                'background-color': '#000',
                'color': '#fff',
                'margin-right': '5px'
            }
        });

        setInterval(() => {
            let num = math.eval($('#box').find('.number-run').attr('data-num') + ' + 3000.23');
            test.run(num.toFixed(2));

            let num2 = math.eval($('#box2').find('.number-run').attr('data-num') + ' + 200.21')
            test2.run(num2.toFixed(2));

            let num3 = math.eval($('#box3').find('.number-run').attr('data-num') + ' + 3421.238')
            test3.run(num3.toFixed(3));
        }, 2000)
    })

</script>

</html>

 

展开阅读全文
加载中

作者的其它热门文章

打赏
0
0 收藏
分享
打赏
0 评论
0 收藏
0
分享
返回顶部
顶部