带 JQuery 的 HTML 倒计时圈

时间:2021-01-17 03:16:07

标签: javascript html jquery css

我在 HTML 中实现这个倒数计时器时遇到了一些问题。它在大多数情况下都有效,但它似乎在乞讨和 ~ i=14 时翻转。我不太确定是什么原因造成的。我认为在 svg 尝试运行之前没有设置变量,但我不确定有什么方法可以解决这个问题。

    <div>
        <div class="item">
            <h2>0</h2>
            <svg width="120" height="120" xmlns="http://www.w3.org/2000/svg">
            <g>
            <title>Layer 1</title>
            <circle id="circle" class="circle_animation" r="56" cy="60" cx="60" stroke-width="8" stroke="#6fdb6f" fill="none"/>
            </g>
            </svg>
        </div>
        <div class="item">
            <h2>0</h2>
            <svg width="120" height="120" xmlns="http://www.w3.org/2000/svg">
            <g>
            <title>Layer 1</title>
            <circle id="circle" class="circle_animation" r="56" cy="60" cx="60" stroke-width="8" stroke="#6fdb6f" fill="none"/>
            </g>
            </svg>
        </div>
    </div>
    <script>
        window.$ = window.jQuery = require('jquery');
        setTimeout(function() { 
            var time = 500; /* how long the timer will run (seconds) */
            var initialOffset = '351';
            var i = 1;

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

            var interval = setInterval(function() {
                $('h2').text(time - i);
                if (i === time) {   
                    clearInterval(interval);
                    return;
                }

                $('.circle_animation').css('stroke-dashoffset', initialOffset+((i+1)*(initialOffset/time)));               
                
                i++;  
            }, 1000);
 
        }, 0)
    </script>

/*css*/

.item {
    position: relative;
    float: left;
}

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

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

.circle_animation {
    stroke-dasharray: 351;
    /* stroke-width: 5px; */
    /* this value is the pixel circumference of the circle */
    stroke-dashoffset: 351;
    transition: all 1s linear;
}

1 个答案:

答案 0 :(得分:0)

更改var initialOffset = 351;

您的 initialOffsetValue 是字符串,您正在对其进行除法。所以将其转换为整数将解决闪烁问题。

Codepen

相关问题