JavaScript 元素着色仅在通过 document.writeln 的文本之后起作用

标签 javascript html

我有一个 js 函数,它接受一个 html 节点并将其从黄色淡入白色。但只有在从 js 文件调用它之前,我通过文档 document.writeln('Hi'); 将文本添加到 body 元素时,它才有效。如果我直接在html文件中写入文本并且不调用document.writeln,那么打开index.html后我看不到淡入淡出效果。

<!DOCTYPE html>
<html>
<head>
    <script src="program.js"></script>
</head>
<body style='width: 100%; height: 100%'>
      Hi
</body>
</html>

JS文件:

'use strict';

document.writeln('Hi'); // If we comment out this line we don't see the fade effect.

// Define a function that sets a DOM node's color
// to yellow and then fades it to white.

var fade = function (node) {
    var color = 1;
    var step = function () {
        var hex = color.toString(16);
        node.style.backgroundColor = '#FFFF' + hex + hex;
        if(color < 15) {
            color++;
            setTimeout(step, 100);
        }
    }
    setTimeout(step, 100);
};
fade(document.body);

编辑:

使用 window.onload 实现淡入淡出功能也没有帮助。

最佳答案

我尝试使用这个,它工作正常,没有任何错误:

document.addEventListener('DOMContentLoaded',function(){
fade(document.body);});

如果 DOM 尚未加载,则无法更改它。所以,这位听众可能会有所帮助。

正如这里所描述的,如果你调用 Document.writeln() ,浏览器会先调用 Document.open() ,所以存在一个现有的 Document 对象。这可能就是您之前添加此行时它起作用的原因。

https://developer.mozilla.org/de/docs/Web/API/Document/write

关于JavaScript 元素着色仅在通过 document.writeln 的文本之后起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33196229/

相关文章:

javascript将日期和时间转换为特定格式

javascript - nodeJs 文件运行中的语法错误

javascript - node.js 的含义是什么?

php 与 jquery html 弹出

JavaScript:从弹出窗口获取值(外部网站)

javascript - 如何使用 jQuery 引用 HTML5 视频元素?

javascript - 单选按钮内的文本

javascript - Express 中的中间件链接

javascript - angularjs 路由器和 jquerys 的 url 片段问题

html - 如何在ReactJS中的图像上添加文本?