
使用document.write向文档输出写内容;
document.write用法:document.write("要输出的内容");
其实document.write()有两种情况:
1.在文档流加载过程中执行代码:document.write会在代码所在位置添加输出内容.如下
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<script type="text/javascript">
document.write("<h1>放在header里的document.write</h1>")
</script>
</head>
<body>
<script type="text/javascript">
document.write("<h1>放在body里的document.write</h1>")
</script>
</body>
</html>
执行结果:
如果写入位置在header里,而且为引入文档,引入文件会被放在head里,但是如果先写非引入文档的内容,引入文档的标签也会写在body里,(这部分没有仔细研究,写项目的时候还没遇到坑... document.write应该会在文档中打开一个开口,然后写入要输入的东西,但是如果不存在html结构文档(只存在引入文档的标签像link,script引入,和meta这些),就会写到head中)
2.在文档流加载完成时执行代码:document.write会重新开启一个文档流覆盖之前网页上存在的文档,页面显示效果就是原先的网页上的内容都消失了,只剩下写入的内容.如下:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<script type="text/javascript">
document.write("<h1>放在header里的document.write</h1>")
</script>
</head>
<body>
<script type="text/javascript">
document.write("<h1>放在body里的document.write</h1>")
setTimeout(function () {
document.write("糟糕文档不见了!")
},2000)
</script>
</body>
</html>
在两秒之后执行结果:
因为在执行document.write()的时候文档已经加载完成,会重新打开一个文档流覆盖之前的文档流.所以原先的文档会消失.