JavaScript时钟的CSS或JavaScript文本转换

时间:2015-09-06 11:06:40

标签: javascript css

我用Javascript制作了一个时钟。这很简单。



var today = new Date();
var h;
if (today.getHours() == 0) h = '12';
else if (today.getHours() < 12) h = today.getHours;
else if (today.getHours() == 12) h = '12';
else h = today.getHours() - 12;
    var m;
if (today.getMinutes() < 10) m = '0' + today.getMinutes();
else m = today.getMinutes();
    var s;
if (today.getSeconds() < 10) s = today.getSeconds();
else s = today.getSeconds();

document.getElementById('time').innerHTML=h + ':' + m + ':' + s;
&#13;
#time {

	top: 20px;
	left: 7px;
	width: 320px;
	font-size: 40px;
	text-align: left;
	font-family: 'Segoe UI Light';

}
&#13;
<body onload="startTime()">
    <div id="main-wrapper"> 
        <div id="center">
            <div id="time"></div>
         </div>
     </div>
</body>
&#13;
&#13;
&#13;

现在,我想做的就是为它添加一个简单的过渡,以便数字在变化时消失。但是,我无法通过CSS或JavaScript找到一个好方法。

这可能是一个简单的问题,但谷歌搜索解决方案(并在Stack Exchange上搜索)只是让我更加困惑。

1 个答案:

答案 0 :(得分:0)

你想要这个吗?您的原始代码不适用于额外的零。这意味着此代码是从头开始的

时钟使用JS + CSS

JS

var c = document.getElementById("clock");
Date.prototype.hhmmss = function() {
    var hh = this.getHours().toString();
    var mm = this.getMinutes().toString();
    var ss  = this.getSeconds().toString();
    return (hh[1]?hh:"0"+hh[0]) + ":" + (mm[1]?mm:"0"+mm[0]) + ":" + (ss[1]?ss:"0"+ss[0]);
};
function clock(){
    c.innerHTML += ("<span class='tick'>"+ new Date().hhmmss()+"</span>");
    setTimeout(function(){     
        var old = c.getElementsByClassName("tick")[0];
        old.className += " remove";
        setTimeout(function(){
            var old = c.getElementsByClassName("tick")[0];
            old.parentNode.removeChild(old);
        },250);
    }, 750);
}
var x = setInterval(function(){clock()}, 1000);

CSS

.tick {
    animation: appear 0.25s ease-out;
    transition: all 0.25s ease-out;
    display:block;
    position:absolute;
    top:0;
    left:0;
}

.tick.remove {
    opacity:0
}

@keyframes appear {
    0% {
        opacity:0; 
    }
    100% {
        opacity:1;
    }
}

jsfiddle:http://jsfiddle.net/pduyqr9v/3/