如何在自行携带的html网页上设置时间函数
How to set time function on html web page which carry on itself?
我想在自动运行的网页上设置时间,所以我有带有 id 属性的 html 代码:
function tellTime() {
var now = new Date();
var theHr = now.getHours();
var theMin = now.getMinutes();
document.write("time: " + theHr + ":" + theMin);
}
document.getElementById("demo").innerHTML = tellTime();
<div id="demo"></div>
因此,当页面重新加载时,似乎是时间,但用户重新加载页面以查看当前时间。
我们如何设置不需要重新加载即可查看当前时间的函数?
使用 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 演示
您可以使用 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
}
你需要使用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>
var myVar = setInterval(myTimer, 1000);
function myTimer() {
var d = new Date();
document.getElementById("demo").innerHTML = d.toLocaleTimeString();
}
<p>A script on this page starts this clock:</p>
<p id="demo"></p>
<button onclick="clearInterval(myVar)">Stop time</button>
http://www.w3schools.com/js/tryit.asp?filename=tryjs_setinterval3
相关文章:
- HTML 5 和 3.js 代码不会在网页上显示任何内容
- 如何在我的html网页中使用jquery自动完成
- 使用服务器上的HTML/js在网页上显示图像
- 使用javascript从HTML网页中提取图像url
- 正在创建网页,并希望将外部链接调用为html和css
- javascript从选中的复选框中检索输入值,并在同一网页中显示多个html文件
- 我可以通过点击html文件中的按钮来记录我的屏幕/网页吗
- 网页's使用Phantom的HTML
- .val() 选择文本而不是值字符串,当网页动态编辑源 html
- 在HTML网页中运行python方法
- 我应该怎么做才能避免在网页上移动元素(html、css、jQuery)
- 使用JavaScript从网页复制HTML代码或图像链接
- 从网页获取数据的更好方法,而不是使用DOM和HTML元素
- 如何在Arduino提供的ESP8266 HTML网页上使用ajax和setInterval
- 在加载html网页时显示JavaScript表
- 获取网页html元素值,而无需使用JavaScript在新窗口或新选项卡中打开页面
- 如何从网页(HTML/Javascript)向Java应用程序发送简单消息
- 转换网页(html)的缩略图/预览输出通过PHP文件
- 实现对网页(HTML)的监控功能
- 压缩整个网页(HTML和JS)