javascript - 将当前时间添加到我页面上的特定部分

标签 javascript html dom

因此,我在 HTML 文件上创建了一个 div id="time" 并将其定位,以便当前时间可以显示在我制作的边框内网站的左上角。因此,我希望当前时间显示在我制作的网站左上角的边框内,但这样做遇到困难:

HTML 文件:

    <div id="time">

    </div>

我的js文件:

var time = document.getElementById("time")

var currentTime = new Date()
var hours = currentTime.getHours()
var minutes = currentTime.getMinutes()

if (minutes < 10)
    minutes = "0" + minutes

var suffix = "AM";
if (hours >= 12) {
    suffix = "PM";
    hours = hours - 12;
}
if (hours == 0) {
    hours = 12;
}

document.write("<b>" + hours + ":" + minutes + " " + suffix + "</b>")

当前时间确实成功显示,但它没有显示在我想要的位置(它一直显示在页面底部)。也许 DOM 有问题?

最佳答案

试试这个:

var time = document.getElementById("time")

var currentTime = new Date()
var hours = currentTime.getHours()
var minutes = currentTime.getMinutes()

if (minutes < 10)
minutes = "0" + minutes

var suffix = "AM";
if (hours >= 12) {
suffix = "PM";
hours = hours - 12;
}
if (hours == 0) {
hours = 12;
}

time.innerHTML = "<b>" + hours + ":" + minutes + " " + suffix + "</b>";
<div id="time">

</div>

使用time.innerHTML = '...'显示在您的div所在的位置。

关于 document.write() 的一些话

Object-Oriented JavaScript - Second Edition: The method document.write() allows you to insert HTML into the page while the page is being loaded. You can have something like the following code:

<p>It is now
    <script>document.write("<em>" + new Date() + "</em>"); </script>
</p> 

This is the same as if you had the date directly in the source of the HTML document as follows:

<p>It is now 
    <em>Fri Apr 26 2013 16:55:16 GMT-0700 (PDT)</em> 
</p>

Note, that you can only use document.write() while the page is being loaded. If you try it after page load, it will replace the content of the whole page. It's rare that you would need document.write(), and if you think you do, try an alternative approach. The ways to modify the contents of the page provided by DOM Level 1 are preferred and are much more flexible.

关于javascript - 将当前时间添加到我页面上的特定部分,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37283356/

相关文章:

javascript - 如何重置最近的跨度对象的文本?

javascript - 过滤器的多个值

javascript - 水平循环轮播 javascript/jquery

javascript - 防止div在上面加载数据后跳下Jquery

javascript - JSC_TRAILING_COMMA : Parse error. IE8(及更低版本)- jshint 可以警告我左尾随逗号吗?

javascript - 导航到 URL 并从 anchor 标记中获取 href 属性?

javascript - DOM 事件composedPath() 方法的文档

javascript - 在 IE 中从输入类型=文件中抓取单个文件

html - CSS 样式表不响应使用 chrome

javascript - 如何用 HTML DOM 替换替换字符串