2016-08-17 36 views
-1

我是html/css/javascript的初学者。我想创建一个时钟,我在这里有代码。但是,这段代码无法正常工作,所以我想我在某个地方有一个错误。模拟时钟发了javascript/html/css不能正常工作

有人可以找到错误,并告诉我如何解决它。

CSS

function clock() { 
 
    var d, h, m, s; 
 

 
    h = 30 * ((d.getHours() % 12) + d.getMinutes()/60); 
 
    m = 6 * d.getMinutes(); 
 
    s = 6 * d.getSeconds(); 
 

 
    setAttr('h-hand', h); 
 
    setAttr('m-hand', m); 
 
    setAttr('s-hand', s); 
 
    setAttr('s-tail', s + 180); 
 

 
    h = d.getHours(); 
 
    m = d.getMinutes(); 
 
    s = d.getSeconds(); 
 

 
    if (h >= 12) { 
 
    setText('suffix', 'PM'); 
 
    } else { 
 
    setText('suffix', 'AM'); 
 
    } 
 

 
    if (h != 12) { 
 
    h %= 12; 
 
    } 
 
}; 
 

 
function setAttr(id, val) { 
 
    var v = 'rotate(' + val + ', 70, 70)'; 
 
    document.getElementById(id).setAttribute('transform', v); 
 
}; 
 

 
function setText(id, val) { 
 
    if (val < 10) { 
 
    val = '0' + val; 
 
    } 
 
    document.getElementById(id).innerHTML = val; 
 
};
#analog-clock { 
 
    width: 140px; 
 
    height: 140px; 
 
} 
 
#clock-face { 
 
    stroke: black; 
 
    fill: #ff9933; 
 
} 
 
#h-hand, 
 
#m-hand, 
 
#s-hand, 
 
#s-tail { 
 
    stroke: black; 
 
    stroke-linecap: round; 
 
} 
 
#h-hand { 
 
    stroke-width: 3px; 
 
} 
 
#m-hand { 
 
    stroke-width: 2px; 
 
} 
 
#s-hand { 
 
    stroke-width: 1px; 
 
}
<div class="analog-clock"> 
 
    <svg width="140" height="140"> 
 
    <circle id="clock-face" cx="70" cy="70" r="65" /> 
 
    <line id="h-hand" x1="70" y1="70" x2="70" y2="38" /> 
 
    <line id="m-hand" x1="70" y1="70" x2="70" y2="20" /> 
 
    <line id="s-hand" x1="70" y1="70" x2="70" y2="12" /> 
 
    <line id="s-tail" x1="70" y1="70" x2="70" y2="56" /> 
 
    <text x="62" y="18">12</text> 
 
    <text x="126" y="76">3</text> 
 
    <text x="66" y="130">6</text> 
 
    <text x="7" y="76">9</text> 
 
    </svg> 
 
    <div style="height: 10px;"></div> 
 
    <div class="time-text"> 
 
    <span id="hr" style="color: #4d0099;">00</span> 
 
    <span style="color: black;">:</span> 
 
    <span id="min" style="color: #006633;">00</span> 
 
    <span style="color: black;">:</span> 
 
    <span style="color: #990000;" id="sec">00</span> 
 
    <span id="suffix">--</span> 
 
    </div> 
 
</div>

+2

究竟什么是你的问题?你的CSS失败了?你的Javascript失败默默无闻?您需要帮助调试问题?您不确定如何将问题简化为最小,完整的代码以允许其他人为您提供帮助? – zhon

回答

2

您需要使用当前日期初始化d变量。您也可以将clock()呼叫置于setInterval函数中,以便每秒钟更新您的时钟。不知道这是否是最佳解决方案,但至少它是有效的。

例子:http://jsbin.com/cegutilavo/edit?js,console,output

线3和40

+0

好的,我添加了我没有的线,并且我的时钟正在工作。 –

4

你有你d变量定义。

声明它

var d = new Date(), 
     h, m, s; 

,它会工作。工作时钟here

+0

看来你的codepen无法正常工作。我添加了var d = new Date();但是,我的代码仍然不起作用。 –

+0

已编辑的codepen url –

+0

'var d = new Date();'是错误的 - 我编辑了答案,以便在函数开始处显示完整字符串,其中声明了所有变量 –