Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

不同时期的document.write #3

Open
Abiel1024 opened this issue Mar 25, 2018 · 0 comments
Open

不同时期的document.write #3

Abiel1024 opened this issue Mar 25, 2018 · 0 comments

Comments

@Abiel1024
Copy link
Owner

使用document.write向文档输出写内容;
document.write用法:document.write("要输出的内容");

其实document.write()有两种情况:文档流加载过程中和文档流加载完成时。他们产生的结果是不一样的。

文档流加载过程中

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>

image
如果写入位置在header里,而且为引入文档,引入文件会被放在head里,但是如果先写非引入文档的内容,引入文档的标签也会写在body里,(这部分没有仔细研究,写项目的时候还没遇到坑... document.write应该会在文档中打开一个开口,然后写入要输入的东西,但是如果不存在html结构文档(只存在引入文档的标签像link,script引入,和meta这些),就会写到head中)

文档流加载完成时

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>

image
因为在执行document.write()的时候文档已经加载完成,会重新打开一个文档流覆盖之前的文档流.所以原先的文档会消失.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant