我有一个正常工作的倒数计时器,我唯一需要多次展示它,我似乎无法让它适用于多个计数器。
工作代码:http://jsfiddle.net/3RpvJ/
我试图制作更多div,如timer1 timer2 enz。但我似乎无法让它工作
window.onload = function() {
canvas = document.getElementById('timer'),
seconds = document.getElementById('counter'),
ctx = canvas.getContext('2d'),
sec = 180,
countdown = sec;
ctx.lineWidth = 8;
ctx.strokeStyle = "#528f20";
var
startAngle = 0,
time = 0,
intv = setInterval(function(){
var endAngle = (Math.PI * time * 2 / sec);
ctx.arc(65, 35, 30, startAngle , endAngle, false);
ctx.clearRect(0, 0, 200, 200);
startAngle = endAngle;
ctx.stroke();
countdown--;
if ( countdown > 60){
seconds.innerHTML = Math.floor(countdown/60);
seconds.innerHTML += ":" + countdown%60;
}
else{
seconds.innerHTML = countdown;
}
if (++time > sec,countdown == 0 )
{
clearInterval(intv),
$("#timer, #counter").remove(),
$("#timers").prepend('<img id="theImg" src="http://ivojonkers.com/votify/upvote.png" />');
}
}, 10);
}
答案 0 :(得分:1)
function Timer(dur, par, can, cnt) {
var parent = $(par),
canvas = can ? $(can, parent)[0] : $('.timer', parent)[0],
seconds = cnt ? $(cnt, parent)[0] : $('.counter', parent)[0],
//ctx = canvas.getContext('2d'),
sec = dur,
countdown = sec;
if (!canvas)
canvas = $("<canvas>").addClass('timer')
.attr('width', 100).attr('height', 100).appendTo(parent)[0];
if (!seconds)
seconds = $("<span>").addClass('counter').appendTo(parent)[0];
var ctx = canvas.getContext('2d');
ctx.lineWidth = 8;
ctx.strokeStyle = "#528f20";
var startAngle = 0,
time = 0,
intv = setInterval(function() {
var endAngle = (Math.PI * time * 2 / sec);
ctx.arc(65, 35, 30, startAngle, endAngle, false);
ctx.clearRect(0, 0, 200, 200);
startAngle = endAngle;
ctx.stroke();
countdown--;
if (countdown > 60) {
seconds.innerHTML = Math.floor(countdown / 60);
seconds.innerHTML += ":" + countdown % 60;
}
else {
seconds.innerHTML = countdown;
}
if (++time > sec, countdown == 0) {
clearInterval(intv);
$(canvas).remove();
$(seconds).remove();
$(par).prepend('<img id="theImg" src="http://ivojonkers.com/votify/upvote.png" />');
}
}, 10);
}
$(function() {
Timer(180, '#timer1');
Timer(240, '#timer2');
Timer(300, '#timer3');
Timer(360, '#timer4');
});
HTML:
<div id="timers">
<div id="timer1" class="time">
</div>
<div id="timer2" class="time">
</div>
<div id="timer3" class="time">
</div>
<div id="timer4" class="time">
</div>
</div>
CSS:
#timers canvas {
-webkit-transform : rotate(-90deg);
-moz-transform : rotate(-90deg);
}
body{
background-color: #242424;
}
#timers .time{
position: relative; z-index: 1; height: 70px; width: 70px; }
#timers span {
position : absolute;
z-index : 1;
top : 50%;
margin-top : -0.6em;
display : block;
width : 100%;
text-align : center;
height : 1.5em;
color : #528f20;
font : 1.3em Arial;
}
我创建了一个Timer函数,它将占用一个持续时间,一个父元素,以及画布和计数器的可选选择器。如果未指定can
和cnt
且不存在,则会创建它们。对于html,我添加了一个额外的分组div,以便每个计时器的所有元素都有一个共同的父级。对于CSS,我更改了您的命名约定以使其更加干燥。每个Timer父div都有“time”类,但这可以是你想要的任何东西。 Timer会假设画布有一类“计时器”,时间输出将有一个“计数器”类。这些也可以是你想要的任何东西,但在这种情况下你必须指定参数。