参考资料

  1. HTML DOM对单个单元格的内容水平对齐
  2. HTML DOM 返回一个表单中所有元素的value 实例
  3. HTML DOM 返回image的name
  4. HTML DOM 节点
  5. HTML DOM 返回一个锚的名字 实例
  6. HTML DOM 哪个鼠标键被点击了?
  7. HTML DOM 修改
  8. HTML DOM 返回图像映射某个区域的坐标实例

HTML DOM 打开输出流,向流中输入文本实例

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. 过度使用可能引发性能问题