参考资料

  1. HTML DOM获得有下拉列表的表单的ID
  2. HTML DOM 返回一个button的value 实例
  3. HTML DOM 返回加载的文档的服务器域名 实例
  4. HTML DOM 对iframe排版
  5. HTML DOM添加表格行中的单元格
  6. HTML DOM 返回文档中第一个图像的ID
  7. HTML DOM 返回文档的最后一次修改时间 实例
  8. HTML DOM 返回一个iframe中的marginwidth属性的值

HTML DOM 输出流操作

简介

HTML DOM 提供了 document.open()document.write() 方法来操作文档输出流,允许动态地向文档中写入内容。

主要方法

document.open()

打开一个文档流用于写入。

document.write()

向文档流中写入HTML或文本内容。

document.close()

关闭文档流。

基本用法

<!DOCTYPE html>
<html>
<head>
    <title>DOM 输出流示例</title>
    <style>
        .output {
            border: 1px solid #ccc;
            padding: 10px;
            margin: 10px 0;
        }
    </style>
</head>
<body>
    <div id="content"></div>

    <script>
        // 打开文档流
        document.open();
        
        // 写入内容
        document.write("<h1>动态写入的内容</h1>");
        document.write("<p>这是通过document.write()方法添加的段落。</p>");
        
        // 关闭文档流
        document.close();
    </script>
</body>
</html>

功能说明

  1. 动态内容生成:可以在页面加载时或之后动态添加内容

  2. 覆盖或追加内容:取决于何时调用这些方法

  3. 性能考虑:频繁使用可能影响性能

高级实例

动态生成表格

<script>
document.open();
document.write("<table border='1'>");
document.write("<tr><th>姓名</th><th>年龄</th></tr>");
document.write("<tr><td>张三</td><td>25</td></tr>");
document.write("<tr><td>李四</td><td>30</td></tr>");
document.write("</table>");
document.close();
</script>

结合CSS样式

<script>
document.open();
document.write("<style>");
document.write(".dynamic-content { color: blue; font-family: Arial; }");
document.write("</style>");
document.write("<div class='dynamic-content'>");
document.write("这段文字使用了动态添加的样式");
document.write("</div>");
document.close();
</script>

注意事项

  1. 在页面加载完成后调用 document.write() 会覆盖整个文档

  2. 现代开发中更推荐使用DOM操作方法如 createElementappendChild

  3. 过度使用可能引发性能问题