如何进行 jQuery 倒计时

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2064186/
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 12:41:41  来源:igfitidea点击:

How can I make a jQuery countdown

jquery

提问by Mostafa Elkady

I want a jQuery countdown:

我想要一个 jQuery 倒计时:

  1. It starts counting after page download finishes
  2. After counting to 0 it redirects to a url
  1. 页面下载完成后开始计数
  2. 计数到 0 后,它重定向到一个 url

How can I do that?

我怎样才能做到这一点?

回答by Sampson

I thought I would break this up a bit and provide something that does both countdown, and redirection. After all, you may want to countdown and manipulate the DOM instead tomorrow. As such, I've come up with the following jQuery plugin that you can use, and study:

我想我会把它分解一下并提供一些既可以倒计时又可以重定向的东西。毕竟,明天您可能想要倒计时和操作 DOM。因此,我想出了以下 jQuery 插件,您可以使用和研究:

// Our countdown plugin takes a callback, a duration, and an optional message
$.fn.countdown = function (callback, duration, message) {
    // If no message is provided, we use an empty string
    message = message || "";
    // Get reference to container, and set initial content
    var container = $(this[0]).html(duration + message);
    // Get reference to the interval doing the countdown
    var countdown = setInterval(function () {
        // If seconds remain
        if (--duration) {
            // Update our container's message
            container.html(duration + message);
        // Otherwise
        } else {
            // Clear the countdown interval
            clearInterval(countdown);
            // And fire the callback passing our container as `this`
            callback.call(container);   
        }
    // Run interval every 1000ms (1 second)
    }, 1000);

};

// Use p.countdown as container, pass redirect, duration, and optional message
$(".countdown").countdown(redirect, 5, "s remaining");

// Function to be called after 5 seconds
function redirect () {
    this.html("Done counting, redirecting.");
    window.location = "http://msdn.microsoft.com";
}

回答by xenioushk

I have create a countdown script using JQUERY, CSS and HTML. Here is my full source code. Demo link also available.

我已经使用 JQUERY、CSS 和 HTML 创建了一个倒计时脚本。这是我的完整源代码。演示链接也可用。

CSS Part:

CSS部分:

<style type="text/css">
    body{ font-family: verdana; font-size:12px; }
    a{text-decoration: none;color:blue;font-weight: bold;}
    a:hover{color: gray;font-weight: bold;}
    div#my-timer{width: 400px;background: lightblue; margin:  0 auto;text-align: center;padding:5px 0px 5px 0px;}
</style>

Jquery Part:

jQuery 部分:

<script type="text/javascript" src="js/jquery-1.4.2.js"></script>
    <script type="text/javascript">
        var settimmer = 0;
        $(function(){
                window.setInterval(function() {
                    var timeCounter = $("b[id=show-time]").html();
                    var updateTime = eval(timeCounter)- eval(1);
                    $("b[id=show-time]").html(updateTime);

                    if(updateTime == 0){
                        window.location = ("redirect.php");
                    }
                }, 1000);

        });
    </script>

HTML Part:

HTML部分:

<div id="my-timer">
        Page Will Redirect with in <b id="show-time">10</b> seconds        
</div>

Demo Link: http://demos.coolajax.net/php/redirect

演示链接:http: //demos.coolajax.net/php/redirect

I hope this code will be a helpful one for you.

我希望此代码对您有所帮助。

回答by nfechner

Are you sure, you want to use Javascript for this? You might just go with plain HTML:

您确定要为此使用 Javascript 吗?您可能只使用纯 HTML:

<meta http-equiv="refresh" content="NUMBER_OF_SECONDS_TO_WAIT; URL=http://REDIRECT_URL/">

Put this in the header and the forward will even work on browsers without Javascript enabled.

把它放在标题中,转发甚至可以在没有启用 Javascript 的浏览器上工作。

回答by n0nag0n

Here's my example based off of Jonathan Sampson's example. Here's the jsfiddle link. http://jsfiddle.net/njELV/1/

这是我基于 Jonathan Sampson 示例的示例。这是 jsfiddle 链接。http://jsfiddle.net/njELV/1/

jQuery:

jQuery:

var countdown = {
    startInterval : function() {
        var count = 1800; // 30 minute timeout
        var currentId = setInterval(function(){
            $('#currentSeconds').html(count);
            if(count == 30) { // when there's thirty seconds...
                $('#expireDiv').slideDown().click(function() {
                        clearInterval(countdown.intervalId);
                        $('#expireDiv').slideUp();                      
                        window.location.reload();
                        //or whatever you'd like to do when someone clicks on the div (refresh your session etc).
                });
            }
            if (count == 0) {
                window.location.href = '/logout.php';
            }
            --count;
        }, 1000);
        countdown.intervalId = currentId;
    }
};
countdown.startInterval();

/*
Then each time an ajax call is made to fetch a page
*/
if(typeof countdown.oldIntervalId != 'undefined') {
        countdown.oldIntervalId = countdown.intervalId;
        clearInterval(countdown.oldIntervalId);
        countdown.startInterval();
        $('#expireDiv').slideUp();
    } else {
        countdown.oldIntervalId = 0;
    }

CSS:

CSS:

#expireDiv {
    width: 100%;
    text-align: center;
    background-color: #63AFD0;
    padding: 10px;
    margin: 0;
    border: 1px solid #024A68;
    color: #024A68;
    font-weight: bold;
    font-size: 125%;
    box-shadow: -1px -1px 5px 1px #5E8C9E inset;
    -moz-box-shadow: -1px -1px 5px 1px #5E8C9E inset;
    -webkit-box-shadow: -1px -1px 5px 1px #5E8C9E inset;
    display:none;
    cursor: pointer;
}

HTML:

HTML:

<div id="expireDiv">
    Your session is about to expire. You will be logged out in <span id="currentSeconds"></span> seconds. If you want to continue, please save your work and click <u>here</u> to refresh the page.
</div>

回答by FDisk

You can use the jQuery animatefunction

您可以使用jQuery 动画功能

// Enter num from and to
$({countNum: 8000}).animate({countNum: 0}, {
  duration: 8000,
  easing:'linear',
  step: function() {
    // What todo on every count
    console.log(Math.floor(this.countNum));
  },
  complete: function() {
    console.log('finished');
  }
});

http://jsbin.com/upazas/1/edit

http://jsbin.com/upazas/1/edit

回答by SaidbakR

I have this simple solution without jquery:

我有这个没有jquery 的简单解决方案:

<script>
    sec = 10;
    counter = document.getElementById('counter');
    counter.innerText = sec;
    i = setInterval(function(){
        --sec;

        if (sec === 1){
            clearInterval(i);
            window.location = document.getElementById('retry').href;
        }
        counter.innerText=sec;
        },1000);
    </script>

In the example above, the redirect URL is extracted from hrefattribute of a hyperlink in the document, which you may replace with any value you want.

在上面的示例中,重定向 URL 是从href文档中超链接的属性中提取的,您可以将其替换为您想要的任何值。

Checkout this DEMO

结帐这个演示

回答by Javad Masoumi

this link useful jQuery Countdownsupport all language

这个链接很有用 jQuery Countdown支持所有语言

just:)

只是:)

<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.6.1/jquery.min.js"></script>
<script type="text/javascript" src="jquery.countdown.js"></script>
<script type="text/javascript">
      $('#mySelector').countdown({since: new Date(2010, 12-1, 25)});
</script>

回答by wtf_lol

In Himel Khan's code example posted above, I changed

在上面发布的 Himel Khan 代码示例中,我更改了

if(updateTime == 0)

if(updateTime == 0)

to

if(updateTime <= 0)

if(updateTime <= 0)

just in case somebody hits the back button after being redirected. Otherwise it will start into negative numbers and never re-redirect.

以防万一有人在被重定向后点击后退按钮。否则它将开始为负数并且永远不会重新重定向。

It is important to note that you should not have the code linked on the target page with this change or it will loop refresh. If you make this change, only include the script on the page with the countdown.

需要注意的是,您不应将代码链接到目标页面上进行此更改,否则会循环刷新。如果进行此更改,请仅在页面上包含倒计时的脚本。

I assume there is a better way to accomplish this fix so maybe somebody else could add a better solution

我认为有更好的方法来完成此修复,所以也许其他人可以添加更好的解决方案

Thank you for the code.

谢谢你的代码。

回答by Azam Alvi

you can use this

你可以用这个

<div id="counter"></div>

<script type="text/javascript" src="http://yourjavascript.com/88131111995/jquery.countdown.js"></script>

    $(document).ready(function () {
     $('#counter').countdown({
        until: 5,
        compact: true,
        onExpiry: function() { alert('bye!!'); }
      });
   });