JavaScript >> Javascript 文檔 >  >> Tags >> CSS

製作一個 jQuery 倒數計時器

在構建即將推出或活動頁面時,您會發現自己正在尋找一種顯示剩餘時間的好方法。倒計時給人一種緊迫感,結合電子郵件字段可以為您的時事通訊帶來更多註冊。

今天我們將構建一個簡潔的 jQuery 插件來顯示倒數計時器。它將顯示您活動的剩余天數、小時數、分鐘數和秒數,以及每秒的動畫更新。 注意: 該插件也可以在 Github 上找到。

讓我們從標記開始吧!

HTML

我們將給插件命名為“倒計時”。在一個空元素上調用,它將用倒數計時器所需的 HTML 填充它。您無需執行任何操作,只需選擇要在其中顯示它的元素。

生成的標記

<div id="countdown" class="countdownHolder">
    <span class="countDays">
        <span class="position">
            <span class="digit static"></span>
        </span>
        <span class="position">
            <span class="digit static"></span>
        </span>
    </span>

    <span class="countDiv countDiv0"></span>

    <span class="countHours">
        <span class="position">
            <span class="digit static"></span>
        </span>
        <span class="position">
            <span class="digit static"></span>
        </span>
    </span>

    <span class="countDiv countDiv1"></span>

    <span class="countMinutes">
        <span class="position">
            <span class="digit static"></span>
        </span>
        <span class="position">
            <span class="digit static"></span>
        </span>
    </span>

    <span class="countDiv countDiv2"></span>

    <span class="countSeconds">
        <span class="position">
            <span class="digit static"></span>
        </span>
        <span class="position">
            <span class="digit static"></span>
        </span>
    </span>

    <span class="countDiv countDiv3"></span>
</div>

在上面的例子中,插件最初是在一個 id 為 countdown 的 div 上調用的 .然後插件添加了一個 countdownHolder class 給它(所以一些樣式通過 CSS 應用於元素)。

裡面是數字的標記。有兩個數字 跨越每個時間單位(天、小時、分鐘和秒),這意味著您可以倒計時到未來不超過 99 天的日期(對於這樣的時間範圍,您可能無論如何都不應該使用計時器,它會令人沮喪)。

數字的靜態類為它們提供了漸變背景和框陰影。當動畫時,這個類被移除,這樣這些 CSS3 觸摸就不會減慢動畫的速度。數字組合在一起,因此您可以輕鬆地為它們設計樣式。向 .countDays 添加字體大小聲明 , 會影響兩個日期數字的大小。

.countDiv 跨度是單元之間的分隔符。冒號由 :before/:after 元素組成。

但是這個標記究竟是如何生成的呢?

jQuery

首先我們寫兩個插件使用的輔助函數:

  • 初始化 生成您在上面看到的標記;
  • switchDigit 採用 .position 跨度並為其內部的數字設置動畫;

將此功能提取為單獨的函數可以讓我們保持插件代碼乾淨。

assets/countdown/jquery.countdown.js

  function init(elem, options){
        elem.addClass('countdownHolder');

        // Creating the markup inside the container
        $.each(['Days','Hours','Minutes','Seconds'],function(i){
            $('<span class="count'+this+'">').html(
                '<span class="position">\
                    <span class="digit static">0</span>\
                </span>\
                <span class="position">\
                    <span class="digit static">0</span>\
                </span>'
            ).appendTo(elem);

            if(this!="Seconds"){
                elem.append('<span class="countDiv countDiv'+i+'"></span>');
            }
        });

    }

    // Creates an animated transition between the two numbers
    function switchDigit(position,number){

        var digit = position.find('.digit')

        if(digit.is(':animated')){
            return false;
        }

        if(position.data('digit') == number){
            // We are already showing this number
            return false;
        }

        position.data('digit', number);

        var replacement = $('<div>',{
            'class':'digit',
            css:{
                top:'-2.1em',
                opacity:0
            },
            html:number
        });

        // The .static class is added when the animation
        // completes. This makes it run smoother.

        digit
            .before(replacement)
            .removeClass('static')
            .animate({top:'2.5em',opacity:0},'fast',function(){
                digit.remove();
            })

        replacement
            .delay(100)
            .animate({top:0,opacity:1},'fast',function(){
                replacement.addClass('static');
            });
    }

偉大的!現在讓我們繼續插件主體。為了更好的可配置性,我們的插件必須接受一個帶有參數的對象——我們計數的時間段的時間戳,以及一個回調函數,在每個刻度上執行並傳遞剩餘時間。為簡潔起見,我從代碼中省略了上面的函數。

assets/countdown/jquery.countdown.js

(function($){

    // Number of seconds in every time division
    var days    = 24*60*60,
        hours   = 60*60,
        minutes = 60;

    // Creating the plugin
    $.fn.countdown = function(prop){

        var options = $.extend({
            callback    : function(){},
            timestamp   : 0
        },prop);

        var left, d, h, m, s, positions;

        // Initialize the plugin
        init(this, options);

        positions = this.find('.position');

        (function tick(){

            // Time left
            left = Math.floor((options.timestamp - (new Date())) / 1000);

            if(left < 0){
                left = 0;
            }

            // Number of days left
            d = Math.floor(left / days);
            updateDuo(0, 1, d);
            left -= d*days;

            // Number of hours left
            h = Math.floor(left / hours);
            updateDuo(2, 3, h);
            left -= h*hours;

            // Number of minutes left
            m = Math.floor(left / minutes);
            updateDuo(4, 5, m);
            left -= m*minutes;

            // Number of seconds left
            s = left;
            updateDuo(6, 7, s);

            // Calling an optional user supplied callback
            options.callback(d, h, m, s);

            // Scheduling another call of this function in 1s
            setTimeout(tick, 1000);
        })();

        // This function updates two digit positions at once
        function updateDuo(minor,major,value){
            switchDigit(positions.eq(minor),Math.floor(value/10)%10);
            switchDigit(positions.eq(major),value%10);
        }

        return this;
    };

    /* The two helper functions go here */
})(jQuery);

tick 函數每秒調用一次。在其中,我們計算給定時間戳和當前日期之間的時間差。 updateDuo 然後函數更新構成時間單位的數字。

插件準備好了! 以下是如何使用它(如演示中所示):

assets/js/script.js

$(function(){

    var note = $('#note'),
        ts = new Date(2012, 0, 1),
        newYear = true;

    if((new Date()) > ts){
        // The new year is here! Count towards something else.
        // Notice the *1000 at the end - time must be in milliseconds
        ts = (new Date()).getTime() + 10*24*60*60*1000;
        newYear = false;
    }

    $('#countdown').countdown({
        timestamp   : ts,
        callback    : function(days, hours, minutes, seconds){

            var message = "";

            message += days + " day" + ( days==1 ? '':'s' ) + ", ";
            message += hours + " hour" + ( hours==1 ? '':'s' ) + ", ";
            message += minutes + " minute" + ( minutes==1 ? '':'s' ) + " and ";
            message += seconds + " second" + ( seconds==1 ? '':'s' ) + " <br />";

            if(newYear){
                message += "left until the new year!";
            }
            else {
                message += "left to 10 days from now!";
            }

            note.html(message);
        }
    });

});

當然,要實現這一點,您必須在頁面中包含倒計時文件夾中的 css 和 js 文件。

完成!

您可以將此腳本用作每個啟動頁面的完美補充。最好的一點是它不使用單個圖像,一切都僅使用 CSS 完成。增加或減少字體大小將導致一切都很好地縮放,你只需要一個 display:none 聲明隱藏你不需要的單位。


Tutorial JavaScript 教程
  1. 在 Reactjs 中構建 Markdown 編輯器

  2. 使用 Notions 公共 API 構建博客

  3. 如何渲染兩個數據數組,例如 Instagaram 故事和在 HomeScreen 上發布?

  4. 為邏輯電路創建一種新語言

  5. 使用 React 錯誤邊界捕獲錯誤

  6. 以編程方式在文本輸入中按左鍵

  7. 我的模態

  1. 2D 視差、產品比較、圖像剪輯等 |模塊星期一 28

  2. 在使用 lodash 轉換值時進行 groupBy 的任何好方法

  3. 如何在 NextJS 中為活動鏈接添加樣式

  4. 在 Javascript 重定向後編輯 HTML 樣式

  5. 將 Dialogflow 代理集成到 React 應用程序中

  6. Bootstrap 4.0 版本:有什麼新功能?

  7. 提交Ajax時如何防止jQuery中的雙擊

  1. 人們喜歡Javascript嗎?

  2. 了解 React 鉤子-UseEffect()

  3. 使用低端 PC 編程的技巧。

  4. 像你一樣的動畫只是不關心 Element.animate