JavaScript >> Javascript 文檔 >  >> jQuery

快速提示:製作一個 jQuery 倒計時計時器

去年,我發布了一個關於構建一個簡潔的倒數計時器的小教程。從那以後,我收到的一個請求是,希望找到一種方法來更改代碼以使其計數 - 顯示自頁面打開以來經過的時間或其他某個時間點。

這實際上很容易,並且會為快速提示做一個很好的主題。所以我們開始吧!

第 1 步:重命名舊版本

首先,您需要從上面鏈接的文章中獲取原始插件的副本,並將其提取到硬盤驅動器的某個位置。現在你不想擁有一個名為 count down 的插件 這算數嗎?我們必須重命名它。更改資產/倒計時的名稱 文件夾和里面的文件恭敬地計數。還要記得更改 index.html 中引用這些文件的路徑。

第 2 步:編寫新內容

只需對插件本身進行少量修改。打開 assets/countup/jquery.contup.js 並進行以下編輯:

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

    var options = $.extend({
        callback    : function(){},
        start       : new Date()    // Changing this to "start"
    },prop);

    // Tename the "left" variable to "passed"
    var passed = 0, d, h, m, s,
        positions;

    init(this, options);

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

    (function tick(){

        // Calculate the passed time
        passed = Math.floor((new Date() - options.start) / 1000);

        // Calculate the passed minutes, hours and days     

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

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

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

        // Number of seconds passed
        s = passed;
        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;
};

要調用插件,只需執行以下操作(這也是您必須放在 script.js 中而不是當前的代碼):

$('#countdown').countup();

或者,如果您想從過去的某個時刻開始計數:

$('#countdown').countup({
    start: new Date(2012, 10, 27, 15, 58, 21) //year, month, day, hour, min, sec
});

這是一個包裝!


Tutorial JavaScript 教程
  1. Node.JS 基礎:處理 Cookie

  2. JavaScript 中的 Concat() 數組方法🚀

  3. 反應並使用 NFS 掛載...?

  4. `Kinx` 作為腳本語言。

  5. 我們可以從關於 Ember.js 的 +50000 條推文中學到什麼

  6. 使用 JavaScript 對值進行排序

  7. 使用 Express 在 NodeJs 中理解和編寫中間件!

  1. 函數的變量總是返回 undefined

  2. 無頭 WebKit 和 PhantomJS

  3. Web開發學習前的推薦工具

  4. 保持 Vue 頁面標題與路由器同步的簡單方法

  5. Canvas API 入門:複雜形狀

  6. Javascript 中的可靠設計原則(第 3 部分)——接口隔離原則和依賴倒置

  7. 我建立了我的個人網站

  1. 快速開始使用 React 日誌記錄

  2. 如何使用 Math.js 加速 Node.js 矩陣計算🌠

  3. 閱讀位置指示器

  4. 清理 node_modules 以獲得更輕量級的 Lambda 函數