首页 > 解决方案 > 模拟时钟 - 带有 Javascript 的 PHP - 日期函数

问题描述

对于我个人的挑战,我正在尝试重新创建一个低保真房间。在房间里,我想显示一个带有当前时间的模拟时钟,完全用 PHP 编程。

我目前能够通过 if 语句对其进行“硬编码”,但现在我想在正确的时间每分钟移动分钟部分。我在网上找不到它,所以我希望你能在这里帮助我!不知何故,我需要使它成为一个 for 循环,但我不知道如何遍历 css 部分。

将不胜感激任何帮助!

            <div class="clock">
                <?php
                    $m = date("i");
                    echo date("h:i:s");
                    
                    //Need to become a for/while loop
                    if ($m == 14){
                        echo '<div id="mins" style="transform: rotate(60deg);"</div>'; 
                    }
                ?>
                <div id="mins"></div>
            </div>
.clock{
    height: 150px;
    width: 150px;
    border-radius: 50%;
    background: white;
    position: absolute;
    left: 45%;
    top: 20%;
}

#mins{
    height: 60px;
    width: 5px;
    left: 50%;
    position: relative;
    transform: translateX(-50%);
    background: black;
    transform: rotate(0deg);
    transform-origin: bottom center;
}

标签: javascriptphphtmldatetime

解决方案


我使用 Javascript 的模拟脚本解决方案。不需要 PHP。

index.php

<div class="clock">
    <div id="hours"></div>
    <div id="minutes"></div>
    <div id="seconds"></div>
</div>

javascript

const updateInMS = 1000;

// Get the HTML elements from the page.
const clock = document.getElementsByClassName('clock')[0];
const htmHours = document.getElementById('hours');
const htmMinutes = document.getElementById('minutes');
const htmSeconds = document.getElementById('seconds');

// Start the timer
startTimer();

function startTimer() {
    // Trigger the tick function that loops the clock
    tick();
}

function tick() {
    setTimeout(function() {
        // Retrieve the date
        const now = new Date();
        const hours = now.getHours();
        const minutes = now.getMinutes();
        const seconds = now.getSeconds();

        const secondsInDegrees = (360 * seconds) / 60;
        const minutesInDegrees = (360 * minutes) / 60;
        const hoursInDegrees = (360 * hours) / 12;

        htmHours.style.transform = 'rotate(' + hoursInDegrees + 'deg)';
        htmMinutes.style.transform = 'rotate(' + minutesInDegrees + 'deg)';
        htmSeconds.style.transform = 'rotate(' + secondsInDegrees + 'deg)';

        tick();
    }, updateInMS);
}

css

.clock {
    height: 150px;
    width: 150px;
    border-radius: 50%;
    background: white;
    position: absolute;
    left: 45%;
    top: 20%;
}

.clock div {
    height: 60px;
    width: 5px;
    left: 50%;
    /* UPDATED THIS TO FIXED: */
    position: fixed;
    transform: translateX(-50%);
    background: black;
    transform: rotate(0deg);
    transform-origin: bottom center;
}

#hours {
    background: black;
}

#minutes {
    background: red;
}

#seconds {
    background: blue;
}

希望你喜欢我的解决方案。


推荐阅读