我有一个 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/