javascript - 如何使用 HTML、CSS 或 JavaScript 创建一个循环倒数计时器?

标签 javascript html css timer

目前,我正在开发一款问答游戏,对于每个问题,我都希望放置一个倒数计时器。我有一些插件,但我希望我能自己创建它。我尝试创建的内容如下图所示。您能告诉我该怎么做吗?

有没有一种方法可以将边框分配给最多指定百分比的周长,这样我就可以给出一个边框,首先是完整的,然后随着每一秒的推进,我可以不断减少/增加它,这样我会以完美的方式得到它。

我希望创建的计时器应该看起来像这样(希望您了解它的蓝色边框是如何每秒增加的):

enter image description here

最佳答案

这是我刚才玩的东西。它结合使用了 SVG、CSS 转换和 JavaScript。您应该能够将其拆开并用作起点...

/**
* The setTimeout({},0) is a workaround for what appears to be a bug in StackSnippets.
* It should not be required. See JSFiddle version.
*/

setTimeout(function() { 

  var time = 10; /* how long the timer will run (seconds) */
  var initialOffset = '440';
  var i = 1

  /* Need initial run as interval hasn't yet occured... */
  $('.circle_animation').css('stroke-dashoffset', initialOffset-(1*(initialOffset/time)));

  var interval = setInterval(function() {
      $('h2').text(i);
      if (i == time) {      
        clearInterval(interval);
        return;
      }
      $('.circle_animation').css('stroke-dashoffset', initialOffset-((i+1)*(initialOffset/time)));
      i++;  
  }, 1000);

}, 0)
.item {
    position: relative;
    float: left;
}

.item h2 {
    text-align:center;
    position: absolute;
    line-height: 125px;
    width: 100%;
}

svg {
   -webkit-transform: rotate(-90deg);
    transform: rotate(-90deg);
}

.circle_animation {
  stroke-dasharray: 440; /* this value is the pixel circumference of the circle */
  stroke-dashoffset: 440;
  transition: all 1s linear;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div class="item html">
    <h2>0</h2>
    <svg width="160" height="160" xmlns="http://www.w3.org/2000/svg">
     <g>
      <title>Layer 1</title>
      <circle id="circle" class="circle_animation" r="70" cy="81" cx="81" stroke-width="8" stroke="#6fdb6f" fill="none"/>
     </g>
    </svg>
</div>

JSFiddle version

关于javascript - 如何使用 HTML、CSS 或 JavaScript 创建一个循环倒数计时器?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29649643/

相关文章:

javascript - 如何减少 "Onload"的延迟?

javascript:如何检查是否在上下文菜单新选项卡上单击了链接

javascript - 在不打开标签的情况下播放 youtube

javascript - 为什么我的自定义滚动条不显示在浏览器中?

css - 拉伸(stretch)图像 CSS?

javascript - jQuery if else 无序列表addClass

php - SQLSTATE[42S02] : Base table or view not found: Laravel

javascript - 使用 JQuery 将 JSON 项目添加到 HTML 列表

css - 任何停止 CSS :hover text-decoration underline on child? 的方法

css - 小屏幕上的背景图像模糊(在 Wordpress/Chrome 编辑器中看起来不错,但在实际手机上它很模糊