实现一个挂钟

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/Stay_Hungry_Stay/article/details/81149326

用js实现一个时钟

实现代码如下

css样式如下:

    body,li{
        margin: 0;
        padding: 0;
        list-style: none;
    }
    .contain{
        margin: 0 auto;
        text-align: center;
        font-size: 20px;
        margin: 10px;
    }
    .big{
        width: 300px;
        height: 300px;
        border-radius: 50%;
        border: 10px solid #000;
        margin: 10px auto;
        position: relative;
    }
    .big div{
        width: 2px;
        height: 12px;
        background: #333;
        position: absolute;
        left: 150px;
        top: 0px;
    }
    .big .active{
        background: green;
        width: 4px;
        height: 18px;
        border-radius: 8px;
    }
    .big li{
        position: absolute;
    }
    .big .small{
        width: 10px;
        height: 10px;
        border-radius: 50%;
        background: red;
        z-index: 2;
        left: 145px;
        top: 145px;
    }
    .big .hour{
        width: 6px;
        height: 90px;
        background: #234;
        left: 147px;
        top: 70px;
        border-radius: 12px;
    }
    .big .min{
        width: 4px;
        height: 120px;
        background: green;
        left: 148px;
        top: 50px;
        border-radius: 8px;
    }
    .big .sec{
        width: 2px;
        height: 150px;
        background: red;
        left: 149px;
        top: 30px;
        border-radius: 2px;
    }

html的基本结构:

<div class="contain">现代式的挂钟</div>
<div class="big">
    <li class="small"></li>
    <li class="hour"></li>
    <li class="min"></li>
    <li class="sec"></li>
</div>

js代码如下:

    var index = 0;
    var big = document.querySelector('.big');
    var lis = document.querySelectorAll('.big li');
    fn();
    setInterval(fn,1000);
    function fn(){
        var date = new Date();
        var s = date.getSeconds();
        var m = date.getMinutes() + s/60;
        var h = date.getHours() + m/60;
         lis[3].style.cssText = "transform-origin:center 120px;transform:rotate("+6*s+"deg);";
         lis[2].style.cssText = "transform-origin:center 100px;transform:rotate("+6*m+"deg);";
         lis[1].style.cssText = "transform-origin:center 80px;transform:rotate("+30*h+"deg);";
    }
    for (var i = 0; i < 60; i++) {
        if(i%5 == 0){
            var div = document.createElement('div');
            div.classList.add('active');
        }else{
            var div = document.createElement('div');
        }
        big.append(div);
    }
    var divs = all('.big div');
    for (var i = 0; i < divs.length; i++) {
        divs[index].style.cssText = "transform-origin:0px 150px;transform:rotate("+6*index+"deg);";
        index++;
    }
展开阅读全文

没有更多推荐了,返回首页