3. 电子时钟自动走动效果 具体要求如下:(1)编写程序,实现电子时钟自动走动效果;(2)提供一个按钮控制电子时钟是否停止走动 ,两个参考图如下,您可以用CSS样式让它更美观,漂亮。
时间: 2023-11-22 14:54:31 浏览: 125
这个任务需要使用 HTML、CSS 和 JavaScript 来实现。下面是一个简单的实现方案:
HTML 代码:
```html
<div id="clock">
<div id="hour-hand" class="hand"></div>
<div id="minute-hand" class="hand"></div>
<div id="second-hand" class="hand"></div>
</div>
<button id="stop-button">停止</button>
```
CSS 代码:
```css
#clock {
width: 200px;
height: 200px;
position: relative;
border-radius: 50%;
border: 5px solid black;
margin: 50px auto;
}
.hand {
position: absolute;
background-color: black;
transform-origin: bottom center;
}
#hour-hand {
width: 10px;
height: 60px;
bottom: 50%;
left: 50%;
margin-left: -5px;
}
#minute-hand {
width: 6px;
height: 80px;
bottom: 50%;
left: 50%;
margin-left: -3px;
}
#second-hand {
width: 2px;
height: 100px;
bottom: 50%;
left: 50%;
margin-left: -1px;
}
#stop-button {
display: block;
margin: 20px auto;
}
```
JavaScript 代码:
```javascript
const hourHand = document.getElementById('hour-hand');
const minuteHand = document.getElementById('minute-hand');
const secondHand = document.getElementById('second-hand');
const stopButton = document.getElementById('stop-button');
let intervalId = null;
function updateClock() {
const now = new Date();
const hours = now.getHours();
const minutes = now.getMinutes();
const seconds = now.getSeconds();
const hourAngle = hours * 30 + minutes / 2;
const minuteAngle = minutes * 6;
const secondAngle = seconds * 6;
hourHand.style.transform = `rotate(${hourAngle}deg)`;
minuteHand.style.transform = `rotate(${minuteAngle}deg)`;
secondHand.style.transform = `rotate(${secondAngle}deg)`;
}
intervalId = setInterval(updateClock, 1000);
stopButton.addEventListener('click', () => {
if (intervalId !== null) {
clearInterval(intervalId);
intervalId = null;
stopButton.textContent = '开始';
} else {
intervalId = setInterval(updateClock, 1000);
stopButton.textContent = '停止';
}
});
```
这个程序使用了 `setInterval` 函数定时更新时钟的指针位置,并且通过按钮控制定时器的启停。你可以将代码复制到一个 HTML 文件中并在浏览器中打开查看效果。
阅读全文