HTML DOM 打开输出流,向流中输入文本实例
2025-04-24
15
参考资料
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>功能说明
动态内容生成:可以在页面加载时或之后动态添加内容
覆盖或追加内容:取决于何时调用这些方法
性能考虑:频繁使用可能影响性能
高级实例
动态生成表格
<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>注意事项
在页面加载完成后调用
document.write()会覆盖整个文档现代开发中更推荐使用DOM操作方法如
createElement和appendChild过度使用可能引发性能问题
声明:本站所有文章资源内容,如无特殊说明或标注,均为采集网络资源。如若本站内容侵犯了原著者的合法权益,可联系本站删除。
本文来自《西里网 . html 网页设计》 -- 发布时间:2025-03-29
本页链接:https://html.ciilii.com/show/news-1652.html
原创声明:本篇文章均为西里网原创,由《DeepSeek-R1 模型》自动生成。内容真实性仅供参考学习。
本作品采用 知识共享署名—非商业性使用—相同方式共享 4.0 国际许可协议 (CC BY-NC-SA 4.0) 进行许可。
