JavaScript 模拟时钟

/**
 * 添加圆钟。
 * @param {HTMLElement} root 容器
 * @param {str} width 宽度
 * @param {str} color 表针颜色
 */
function createClock(root, width = '100px', color = '#000') {
    
    
    var svg = '<svg xmlns="http://www.w3.org/2000/svg" viewBox="-50 -50 100 100" width="' + width + '">' +
        '<line x1="0" y1="0" x2="0" y2="-25" stroke="' + color + '" stroke-width="4"/>' +
        '<line x1="0" y1="0" x2="0" y2="-35" stroke="' + color + '" stroke-width="4"/>' +
        '<line x1="0" y1="0" x2="0" y2="-40" stroke="' + color + '" stroke-width="1"/>' +
        '<circle cx="0" cy="0" r="48" stroke="' + color + '" stroke-width="4" fill="transparent"/>' +
        '</svg>';
    root.innerHTML = svg;
    let children;
    var init = function () {
    
    
        children = root.children[0].children;
    }
    var setAngle = function (obj, ang) {
    
    
        var v = 'transform:' + 'rotate(' + ang + 'deg);';
        obj.setAttribute('style', v + '-ms-' + v + '-moz-' + v + '-webkit-' + v + '-o-' + v);
    }
    setInterval(function () {
    
    
        if (!children) init();
        let now = new Date()
        let hours = now.getHours();
        let sec = now.getSeconds();
        let min = now.getMinutes();
        setAngle(children[0], parseInt(hours * 30 + min * 0.5));
        setAngle(children[1], parseInt(min * 6 + sec * 0.1));
        setAngle(children[2], parseInt(sec * 6));
        now = null;
    }, 1);
    init();
}

猜你喜欢

转载自blog.csdn.net/dscn15848078969/article/details/111464630