如何使用 jQuery 创建倒数计时器?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7235816/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 23:34:42  来源:igfitidea点击:

How to create a countdown timer with jQuery?

jqueryhtmlcsstimercountdown

提问by Only Bolivian Here

I'll have more than one of these small boxes on my site, and each will start counting down at different times.

我的网站上会有不止一个这样的小盒子,每个盒子都会在不同的时间开始倒计时。

How can I decrease the numerical value of the timer per second, giving the simulation of a countdown timer?

如何减少计时器每秒的数值,模拟倒数计时器?

enter image description here

在此处输入图片说明

<p class="countdown">15</p>

Using this javascript it correctly countsdown, but every single auctionbox is affected. How would you suggest I isolate the timer to act on only one item?

使用此 javascript 可以正确倒计时,但每个拍卖箱都会受到影响。您如何建议我隔离计时器以仅处理一项?

<script>
var sec = 15
var timer = setInterval(function() {
   $('.auctiondiv .countdown').text(sec--);
   if (sec == -1) {
      $('.auctiondiv .countdown').fadeOut('slow');
      clearInterval(timer);
   }
}, 1000);
</script>

enter image description here

在此处输入图片说明

回答by JaredPar

Try the following which will properly issue the count down for the selected values.

尝试以下将正确发出所选值的倒计时。

$(document).ready(function() {

  // Function to update counters on all elements with class counter
  var doUpdate = function() {
    $('.countdown').each(function() {
      var count = parseInt($(this).html());
      if (count !== 0) {
        $(this).html(count - 1);
      }
    });
  };

  // Schedule the update to happen once every second
  setInterval(doUpdate, 1000);
});

JSFiddle Example

JSFiddle 示例

Note: This will run the count down sequence on every element which has the countdownclass. If you'd like to make it more restrictive to a single element you'll need to alter the selector from .countdownto something more restrictive. The easiest way is to add an id and reference the item directly.

注意:这将在每个具有countdown该类的元素上运行倒计时序列。如果您想让它对单个元素更具限制性,则需要将选择器更改为.countdown更具限制性的内容。最简单的方法是添加一个 id 并直接引用该项目。

<p id='theTarget'>15</p>

The JavaScript is a little more complex here because you'll want the timer to eventually shut off since there's not much chance, or use, of element with a duplicate id being added

这里的 JavaScript 有点复杂,因为您希望计时器最终关闭,因为添加重复 id 的元素的机会或使用不多

$(document).ready(function() {

  var timer = setInterval(function() {

    var count = parseInt($('#theTarget').html());
    if (count !== 0) {
      $('#theTarget').html(count - 1);
    } else {
      clearInterval(timer);
    }
  }, 1000);
});

JSFiddle Example

JSFiddle 示例

回答by Naftali aka Neal

HTML:

HTML:

<p id="countdown">15</p>

JS:

JS:

var count = document.getElementById('countdown');
timeoutfn = function(){
       count.innerHTML = parseInt(count.innerHTML) - 1;
       setTimeout(timeoutfn, 1000);
};
setTimeout(timeoutfn, 1000);

Fiddle: http://jsfiddle.net/wwvEn/

小提琴:http: //jsfiddle.net/wwvEn/

回答by josh.trow

You don't need jQuery for this (though it will help in setting the text).

为此,您不需要 jQuery(尽管它有助于设置文本)。

setIntervalis what you want.

setInterval是你想要的。

$.each(
    $('.countdown'), function(el) { 
         setInterval( function() { 
             $(this).text($(this).text()*1 - 1);
         }, 1000); 
    }
);

回答by Malvolio

var countDown = function() {
    var ct = 15;
    var $elem = $(this);
    var display = function() {
       $elem.text(ct--);
    }
    var iv = setInterval(function() {
        display();
        if (ct === 0) {
          clearInterval(iv);
        }
    }, 1000);
    display();
};
$("#countdown").each(countDown);

回答by Fezal halai

CountdownTimer is a reverse count down jQuery plugin for displaying countdown as per need with its different configuration options.

CountdownTimer 是一个反向倒计时 jQuery 插件,用于根据需要使用不同的配置选项显示倒计时。

A minimal jQuery countdown clock plugin which allows you to count down to a target date time with the support of custom UTC Timezone offset.

一个最小的 jQuery 倒计时时钟插件,它允许您在支持自定义 UTC 时区偏移的情况下倒计时到目标日期时间。

enter image description here

在此处输入图片说明

How to use it:

如何使用它:

jQuery library and the jQuery countdown clock plugin in your web page.

jQuery 库和网页中的 jQuery 倒计时时钟插件。

<script type="text/javascript">
    function SetTimer()
    {
        if(document.SetDefaultTimer != true){ 
            SetDefaultTimeOut(); 
        } 
    }

    function SetDefaultTimeOut()
    {
        //document.SetDefaultTimer = true;
        setTimeout(function () {
            StartTimeOut();             
            $("#videos-container4").css("display", "block");
        }, $("#HdnSetDefaultTime").val());
    }

    function SetTimerByContinue()
    {
        document.SetDefaultTimer = true;
        setTimeout(function () {
            StartTimeOut();             
            $("#videos-container4").css("display", "block");
        }, $("#HdnSMDIdleNotificationRepeatTime").val());
        //}, 600000);
    }

    function ResetTimer()
    {
        $("#videos-container4").css("display", "none");
        clearInterval(cleanTimeOutInterval);
        //SetDefaultTimeOut();
        SetTimerByContinue();
    }

    $('#ClickContinue').click(function () {
        ResetTimer();
    });

    var cleanTimeOutInterval;
    function StartTimeOut() {
        debugger
        var timer2 = $("#HdnTimerCountDownStart").val() + ":00";
        $('.countdown').html($("#HdnTimerCountDownStart").val() + "mins" + ":00" + "secs");
        cleanTimeOutInterval = setInterval(function () {
            var timer = timer2.split(':');
            //by parsing integer, I avoid all extra string processing
            var minutes = parseInt(timer[0], 10);
            var seconds = parseInt(timer[1], 10);
            --seconds;
            minutes = (seconds < 0) ? --minutes : minutes;
            if (minutes < 0) clearInterval(interval);
            seconds = (seconds < 0) ? 59 : seconds;
            seconds = (seconds < 10) ? '0' + seconds : seconds;
            //minutes = (minutes < 10) ?  minutes : minutes;
            //$('.countdown').html(minutes + ':' + seconds);
            if(minutes == "0"){
                $('.countdown').html(seconds + 'secs');
            } else {
                $('.countdown').html(minutes + 'mins ' + seconds + 'secs');
            }
            timer2 = minutes + ':' + seconds;

            if (timer2 == "0:00") {
                //Your action below
            }
        }, 1000);
    }
</script>

Create the Html for a countdown clock using unordered list.

使用无序列表为倒计时时钟创建 Html。

<div id="videos-container4" class="container-fluid main-timer">
    <a href="javascript:void(0);" id="btnAnchor" onclick="SetTimer()" runat="server">Timer</a>
    <input type="hidden" id="HdnSetDefaultTime" value="0" />
    <input type="hidden" id="HdnSMDIdleNotificationRepeatTime" value="0" />
    <input type="hidden" id="HdnTimerCountDownStart" value="0" />
    <span>Your Time will be end in </span>
    <br />
    <span style="color: red;">
        <span class="countdown"></span>
    </span>
    <!-- <span>minutes</span> -->
    <div style="margin-top: 10px;">
        <a id="ClickContinue" class="btn-continue">Continue</a>
    </div>
</div>

Add the following CSS snippets to style the countdown clock.

添加以下 CSS 片段来设置倒计时时钟的样式。

<style type="text/css">
    .main-timer {
        margin: 10px 15px;
        display: none;
        float: right;
        border: 1px solid #fd0000;
        border-radius: 15px;
        padding-top: 8px;
        height: 100px;
        width: 17%;
        text-align: center;
        background: #fff;
        box-shadow: 0 4px 16px -4px #888;
        position: relative;
    }

    .btn-continue {
        cursor: pointer;
        border: 1px solid #ff0707;
        padding: 4px;
        margin-right: 6px;
        color: green;
        text-decoration: none;
    }

        .btn-continue:hover {
            border: 2px solid #ff0707;
            color: green;
            text-decoration: none;
        }
</style>

回答by Mohsen

Try this in your inspector to get the idea how a countdown timer should work:

在您的检查器中尝试此操作以了解倒数计时器应如何工作:

var count = 15; setInterval("if(count>0)console.log(count--)", 1000)

And here is full code for your case(no jquery)

这是您案例的完整代码(没有 jquery)

var counter = document.getElementsByClassName('countdown')[0],
    count = parseInt(counter);
setInterval("if(count>0)counter.innerHTML(count--)", 1000)