是否可以在Chrome浏览器的网页中动态显示当前时间?

时间:2015-01-09 06:37:29

标签: javascript google-chrome google-chrome-extension

我需要的是在我使用Chrome浏览器访问的网页中动态显示当前时间,就像它插入原始网页一样,或者它可以显示为背景... ?

1 个答案:

答案 0 :(得分:1)

我不知道你想要做什么...但是可以使用Date对象轻松读取当前时间。创建不带任何参数的新Date对象将导致当前时间Date对象。

要将其插入页面,您可以执行以下操作:

// Create a div and append it to the <body>
var div = document.createElement("div");

div.id = "time";
document.body.appendChild(div);

function clock() {
    var now = new Date(),
        h = now.getHours(),
        m = now.getMinutes(),
        s = now.getSeconds();

    // Put the current time (hh:mm:ss) inside the div
    div.textContent = 
    (h>9 ? "" : "0") + h + ":" +
    (m>9 ? "" : "0") + m + ":" +
    (s>9 ? "" : "0") + s;
}

// Execute clock() every 1000 milliseconds (1 second)
setInterval(clock, 1000);

上面的代码将在页面内插入一个div,并使用当前时间每秒更新其文本,如时钟。现在你应该将它设计为始终可见,如下所示:

#time {
    position: fixed;
    z-index: 999999999;
    top: 0;
    left: 0;
} 

上面的CSS会修复页面左上角的元素。您可以根据需要设置样式并将其移动到页面的其他部分。