javascript / jquery 时间倒计时
我想使用纯 Javascript 或受益于 jquery 来制作一个函数来倒计时结束时间,例如:
//consumes a javascript date object
function countDown(endtimme){
...
}
并且它应该显示在 html 中,例如
<div id="time_left_box">
<h1>Time remaining</h1>:
<p>hours left: ..remaining day will be here## <p>
<p>minutes left: ##remaining day will be here## <p>
<p>seconds left: ##remaining day will be here## <p>
</div>
Indeed,如果它可以每秒刷新自己,那就更好了。
我对 javascript 非常天真,并且对如何处理感到困惑,任何帮助将不胜感激。
I want to make a function either using pure Javascript or also benefiting from jquery to count down to an ending time such as:
//consumes a javascript date object
function countDown(endtimme){
...
}
and it should display in html such as
<div id="time_left_box">
<h1>Time remaining</h1>:
<p>hours left: ..remaining day will be here## <p>
<p>minutes left: ##remaining day will be here## <p>
<p>seconds left: ##remaining day will be here## <p>
</div>
Indeed and it would be even more great if it can refresh itself every second.
I am very naive with javascript and confused about how to approach, any help would be appreciate.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您可以使用 jQuery 倒计时
You could use jQuery Countdown
看看这个:http://keith-wood.name/countdown.html
Take a look at this one: http://keith-wood.name/countdown.html
它可以在 JavaScript 中完成,无需插件。
您需要获取当前日期时间,精确到比您显示的时间小一的分母。就您的示例而言,这意味着您需要将所有内容都降低到毫秒。
然后您会发现现在与所需时间之间的差异。这是以毫秒为单位提供给您的。
因为这是以毫秒为单位返回的,所以您需要将它们转换为秒、分钟、小时、天等...这意味着确定每个分母中有多少毫秒。然后您可以使用取模和除法来返回每个单位所需的数字。见下文。
获得想要显示的分母后,您可以通过不同的方法将其返回到 html 页面。例如:
这总结了你的方法。但是,要使其按设定的时间间隔运行(这就是您在 JavaScript 函数中更新 HTML 显示的原因),您需要调用以下函数,给出您的函数名称并提供以毫秒为单位的时间间隔。
It can be done in JavaScript without plugins.
You need to get the current date time, down to the denominator that is one smaller than what you are displaying. With your example, this would mean you need to get everything down to milliseconds.
You then find the difference between now and the desired time. This is given to you in milliseconds.
Because this is returned in milliseconds you need to convert them into seconds, minutes, hours, days etc... This means establishing how many milliseconds are in each denominator. Then you are able to use mod and divide to return the number needed for each unit. See below.
Once you have the denominators you want to display you can return this to the html page through different methods. For example:
That sums up your method. However, to make it run on a set interval (which is why you update the HTML display within the JavaScript function) you need to call the following function, giving your function name and provide your interval in terms of milliseconds.