如何在自己进行的html网页上设置时间功能?

时间:2016-02-29 09:39:42

标签: javascript html

我想在网页上自动设置时间,所以我有带id属性的HTML代码:

<div id="demo">

</div>

和JS函数为用户腾出时间:

function tellTime() {
var now = new Date();
var theHr = now.getHours();
var theMin = now.getMinutes();
document.write("time: " + theHr + ":" + theMin);
}
document.getElementById("demo").innerHTML = tellTime();

因此,当页面重新加载时,似乎是时间,但用户muss重新加载页面以查看当前时间。

我们如何设置功能,无需重新加载以查看当前时间是什么?

感谢

4 个答案:

答案 0 :(得分:0)

<!DOCTYPE html>
<html>
<body>

<p>A script on this page starts this clock:</p>

<p id="demo"></p>

<button onclick="clearInterval(myVar)">Stop time</button>

<script>
var myVar = setInterval(myTimer ,1000);
function myTimer() {
    var d = new Date();
    document.getElementById("demo").innerHTML = d.toLocaleTimeString();
}
</script>

</body>
</html>

http://www.w3schools.com/js/tryit.asp?filename=tryjs_setinterval3

答案 1 :(得分:0)

使用setInterval()

function tellTime() 
{
    var now = new Date(),
        hrs = now.getHours(),
        min = now.getMinutes(),
        sec = now.getSeconds();

    document.getElementById("demo").innerHTML = ("time: " + hrs + ":" + min + ':' + sec);
}

window.setInterval(tellTime, 1000);

jsFiddle Demo

答案 2 :(得分:0)

你可以使用setTimeout自动刷新它或者发一个事件(例如点击事件)来重新加载时间,使用setTimeout你可以像这样每秒刷新时间:

function tellTime() {
    var now = new Date();
    var theHr = now.getHours();
    var theMin = now.getMinutes();
    return "time: " + theHr + ":" + theMin;
}

function printTime() {
    document.getElementById("demo").innerHTML = tellTime();
    setTimeout(printTime, 1000); // Run this function again after a second
}

答案 3 :(得分:0)

您需要使用setInterval

function tellTime() {
   var now = new Date();
   var theHr = now.getHours();
   var theMin = now.getMinutes();
   var theSec = now.getSeconds();
   return "time: " + theHr + ":" + theMin + ":" + theSec;
}
setInterval(function() {
   document.getElementById("demo").innerHTML = tellTime();
}, 1000);
<div id="demo">
</div>